import xml.etree.ElementTree as ET
import mysql.connector

# ---- CONFIGURATION ----
DB_CONFIG = {
    "host": "localhost",
    "port": "8889",  # Mets le bon port MySQL
    "user": "root",
    "password": "root",
    "database": "vroomly-api"
}
XML_FILE = "/Users/petrusedgar/Downloads/PrixCarburants_quotidien_20250309.xml"

# ---- CONNEXION À MYSQL ----
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor(buffered=True)  # ✅ Cursor bufferisé pour éviter les erreurs

def safe_int(value):
    """ Convertit une valeur en int, en gérant les erreurs. """
    try:
        return int(float(value))  # Convertit en float puis en int
    except ValueError:
        return 0  # Retourne 0 si conversion impossible

# ---- CHARGEMENT DU FICHIER XML ----
tree = ET.parse(XML_FILE)
root = tree.getroot()

# ---- PRÉCHARGEMENT DES ID DE CARBURANTS ----
cursor.execute("SELECT id, alias FROM carburant")
carburant_ids = {alias: id for id, alias in cursor.fetchall()}  # ✅ Dictionnaire pour éviter les requêtes répétées

# ---- TRAITEMENT DES PDVs ----
rupture_data = []
for pdv in root.findall("pdv"):
    pdv_id = int(pdv.get("id"))
    latitude = float(safe_int(pdv.get("latitude"))) / 100000
    longitude = float(safe_int(pdv.get("longitude"))) / 100000
    cp = pdv.get("cp")
    adresse = pdv.find("adresse").text if pdv.find("adresse") is not None else ""
    ville = pdv.find("ville").text if pdv.find("ville") is not None else ""

    # Vérifier si la station existe
    cursor.execute("SELECT id FROM station WHERE id_station = %s", (pdv_id,))
    result = cursor.fetchone()
    
    if not result:
        print(f"⚠️ Station {pdv_id} non trouvée, rupture ignorée.")
        continue  # Passe au PDV suivant
    
    idStation = result[0]  # ✅ On récupère l'ID réel

    # ---- TRAITEMENT DES RUPTURES ----
    for rupture in pdv.findall("rupture"):
        carburant_nom = rupture.get("nom")
        modified_at = rupture.get("debut")  # Date de modification

        # Vérifier si le carburant existe
        carburant_id = carburant_ids.get(carburant_nom)
        if not carburant_id:
            print(f"⚠️ Carburant {carburant_nom} inconnu, rupture ignorée.")
            continue

        # Ajouter les données pour batch insert/update
        rupture_data.append((idStation, carburant_id, modified_at))

# ---- OPTIMISATION : INSERT OU UPDATE EN LOT ----
if rupture_data:
    cursor.executemany("""
        INSERT INTO carburantlist (station_id, carburant_id, modified_at, rupture)
        VALUES (%s, %s, %s, 1)
        ON DUPLICATE KEY UPDATE 
            modified_at = VALUES(modified_at), 
            rupture = 1
    """, rupture_data)
    conn.commit()  # ✅ Un seul commit pour toutes les insertions/mises à jour

# ---- FERMETURE DE LA CONNEXION ----
cursor.close()
conn.close()

print("✅ Importation terminée avec succès ! 🚀")
