#!/usr/bin/env python3
"""
═══════════════════════════════════════════════════════════════
🔐 HASH CALCULATOR - ICHIGRIDEA PIPELINE
═══════════════════════════════════════════════════════════════
Calcule les SHA-256 de tous les fichiers et met à jour HASHMAP.json

Usage:
    python hash_calculator.py [--update] [--verify]
"""

import hashlib
import json
import os
from datetime import datetime
from pathlib import Path


def calculate_sha256(filepath: str) -> str:
    """Calcule le SHA-256 d'un fichier"""
    sha256_hash = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()


def count_lines(filepath: str) -> int:
    """Compte les lignes d'un fichier"""
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        return sum(1 for _ in f)


def scan_modules(include_dir: str = "Include") -> dict:
    """Scanne tous les modules MQH"""
    modules = {}
    
    for filepath in Path(include_dir).glob("*.mqh"):
        module_name = filepath.stem
        modules[module_name] = {
            "sha256": calculate_sha256(str(filepath)),
            "lines": count_lines(str(filepath)),
            "file": str(filepath),
            "last_modified": datetime.fromtimestamp(
                filepath.stat().st_mtime
            ).isoformat()
        }
    
    return modules


def update_hashmap(output_file: str = "HASHMAP.json"):
    """Met à jour le fichier HASHMAP.json"""
    
    # Scanner les modules
    modules = scan_modules()
    
    # Hash du fichier principal
    main_ea = {}
    if os.path.exists("IchiGridEA.mq5"):
        main_ea["IchiGridEA.mq5"] = {
            "sha256": calculate_sha256("IchiGridEA.mq5"),
            "lines": count_lines("IchiGridEA.mq5")
        }
    
    # Créer le hashmap
    hashmap = {
        "version": "1.0.0",
        "generated_at": datetime.utcnow().isoformat() + "Z",
        "algorithm": "SHA-256",
        "encoding": "UTF-8",
        "modules": modules,
        "main_ea": main_ea,
        "statistics": {
            "total_modules": len(modules),
            "total_lines": sum(m["lines"] for m in modules.values())
        }
    }
    
    # Écrire le fichier
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(hashmap, f, indent=2, ensure_ascii=False)
    
    print(f"✅ {output_file} mis à jour")
    print(f"   Modules: {len(modules)}")
    print(f"   Lignes totales: {hashmap['statistics']['total_lines']}")
    
    return hashmap


def verify_hashmap(hashmap_file: str = "HASHMAP.json") -> bool:
    """Vérifie l'intégrité des fichiers vs le hashmap"""
    
    with open(hashmap_file, "r", encoding="utf-8") as f:
        hashmap = json.load(f)
    
    errors = []
    
    # Vérifier chaque module
    for module_name, info in hashmap.get("modules", {}).items():
        filepath = info.get("file")
        if not filepath or not os.path.exists(filepath):
            errors.append(f"❌ Fichier manquant: {filepath}")
            continue
        
        current_hash = calculate_sha256(filepath)
        if current_hash != info.get("sha256"):
            errors.append(f"⚠️ Hash modifié: {module_name}")
            errors.append(f"   Attendu: {info.get('sha256')[:16]}...")
            errors.append(f"   Actuel:  {current_hash[:16]}...")
    
    # Vérifier le main EA
    for filename, info in hashmap.get("main_ea", {}).items():
        if os.path.exists(filename):
            current_hash = calculate_sha256(filename)
            if current_hash != info.get("sha256"):
                errors.append(f"⚠️ Hash modifié: {filename}")
    
    if errors:
        print("\n".join(errors))
        return False
    else:
        print("✅ Tous les hashes sont valides")
        return True


if __name__ == "__main__":
    import sys
    
    if "--update" in sys.argv:
        update_hashmap()
    elif "--verify" in sys.argv:
        success = verify_hashmap()
        sys.exit(0 if success else 1)
    else:
        print(__doc__)
        print("\nCommandes:")
        print("  --update  Met à jour HASHMAP.json")
        print("  --verify  Vérifie l'intégrité des fichiers")
