import os
import re
import hashlib
import mysql.connector

# ========= CONFIG MYSQL ==========
DB_CONFIG = {
    "host": "localhost",
    "user": "root",          
    "password": "gHZ5k4MdXhV8s5cpXNzd",  # ton mot de passe MySQL
    "database": "cartos"
}
# =================================

# Chemin vers la base de cartos
BASE_DIR = "/var/www/html/modification_carto/base/"

# Connexion MySQL
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()

def sha1_file(filepath: str) -> str:
    """Calcule le SHA1 d'un fichier"""
    h = hashlib.sha1()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()

def detect_hw_sw(data: bytes):
    """Retourne (hw, sw, ecu_type) si trouvés"""
    text = "".join(chr(b) if 32 <= b < 127 else " " for b in data)

    hw, sw, ecu_type = None, None, None

    # Bosch HW ex: 0281013518
    hw_match = re.search(r"0281\d{6,7}", text)
    if hw_match:
        hw = hw_match.group()
        ecu_type = "Bosch"

    # Bosch SW ex: 1039S12345 ou 1037xxxxxx
    sw_match = re.search(r"103[0-9A-Z]\w+", text)
    if sw_match:
        sw = sw_match.group()
        if ecu_type is None:
            ecu_type = "Bosch"

    # Siemens SID
    sid_match = re.search(r"SID\d+\w*", text)
    if sid_match:
        sw = sid_match.group()
        ecu_type = "Siemens SID"

    # Delphi DCM
    dcm_match = re.search(r"(DCM\d+|966\d+)", text)
    if dcm_match:
        sw = dcm_match.group()
        ecu_type = "Delphi DCM"

    # Marelli IAW
    iaw_match = re.search(r"IAW\w+", text)
    if iaw_match:
        sw = iaw_match.group()
        ecu_type = "Marelli IAW"

    return hw, sw, ecu_type

def process_file(filepath: str, marque: str):
    """Analyse un fichier carto et insère en DB"""
    try:
        filesize = os.path.getsize(filepath)
        filehash = sha1_file(filepath)

        # Vérifie si déjà présent
        cursor.execute("SELECT id FROM ecu_files WHERE hash=%s", (filehash,))
        if cursor.fetchone():
            print(f"[SKIP] {filepath} (déjà en base)")
            return

        # Lecture fichier
        with open(filepath, "rb") as f:
            data = f.read()

        hw, sw, ecu_type = detect_hw_sw(data)

        cursor.execute("""
            INSERT INTO ecu_files (marque, filename, filesize, hw, sw, ecu_type, hash)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """, (marque, os.path.basename(filepath), filesize, hw, sw, ecu_type, filehash))
        conn.commit()

        print(f"[OK] {filepath}")
        print(f"     ECU: {ecu_type} | HW: {hw} | SW: {sw} | Taille: {filesize}")

    except Exception as e:
        print(f"[ERROR] {filepath} -> {e}")

def scan_directory(base_dir: str):
    """Scan récursivement un dossier"""
    for root, dirs, files in os.walk(base_dir):
        marque = os.path.basename(root) if root != base_dir else None
        for file in files:
            print(f"[SCAN] {file}")  # log debug
            if file.lower().endswith((".bin", ".ori", ".mod")):
                filepath = os.path.join(root, file)
                process_file(filepath, marque)

if __name__ == "__main__":
    print(f"=== Scan du dossier {BASE_DIR} ===")
    scan_directory(BASE_DIR)
    print("=== Terminé ===")
    cursor.close()
    conn.close()
