import os
import requests
import xml.etree.ElementTree as ET
import mysql.connector
import zipfile
import io
from datetime import datetime, timedelta
import time

# ---- CONFIGURATION ----
DB_CONFIG = {
    "host": "localhost",
    "port": "3306",
    "user": "naje4034_autoconso_admin",
    "password": "Francisco$*1401",
    "database": "naje4034_autoconso_api"
}

date_j2 = (datetime.now() - timedelta(days=2)).strftime("%Y%m%d")
XML_FILE = f"https://donnees.roulez-eco.fr/opendata/jour/{date_j2}"
SAVE_DIR = "./public/xml"

# ---- CRÉATION DU DOSSIER ----
if not os.path.exists(SAVE_DIR):
    os.makedirs(SAVE_DIR)

# ---- TÉLÉCHARGEMENT DU FICHIER XML OU ZIP ----
response = requests.get(XML_FILE)
if response.status_code == 200:
    content_type = response.headers.get('Content-Type')
    print("Type de contenu :", content_type)

    if 'zip' in content_type:
        # Décompresse le contenu ZIP
        with zipfile.ZipFile(io.BytesIO(response.content)) as z:
            z.extractall(SAVE_DIR)
            print("Fichiers extraits :", z.namelist())
            # Supposons que le fichier XML extrait est le premier
            extracted_file = os.path.join(SAVE_DIR, z.namelist()[0])
    elif 'xml' in content_type:
        # Si c'est déjà un XML
        extracted_file = os.path.join(SAVE_DIR, f"PrixCarburants_quotidien_{date_j2}.xml")
        with open(extracted_file, 'wb') as file:
            file.write(response.content)
        print("Fichier XML téléchargé.")
    else:
        print("Le contenu téléchargé n'est pas un XML valide ni un ZIP.")
        exit(1)
else:
    print(f"Erreur lors du téléchargement : {response.status_code}")
    exit(1)

# ---- PARSING DU FICHIER XML ----
try:
    tree = ET.parse(extracted_file)
    root = tree.getroot()
    # Continuez avec le traitement du XML ici...
except ET.ParseError as e:
    print(f"Erreur de parsing : {e}")
    exit(1)

# (Le reste de votre code pour insérer dans la base de données)
# ---- CONNEXION À MYSQL ----
try:
    conn = mysql.connector.connect(**DB_CONFIG)
    cursor = conn.cursor()
except mysql.connector.Error as e:
    print(f"Erreur de connexion à la base de données : {e}")
    exit(1)

# ---- CRÉATION DES TABLES ----
# (Votre code pour créer les tables reste inchangé)

# Fonction pour insérer un service dans la base de données
def insert_service(service_name):
    sql = '''INSERT IGNORE INTO services(name) VALUES(%s)'''
    cursor.execute(sql, (service_name,))
    conn.commit()

def safe_int(value):
    try:
        return int(float(value))  # Convertit en float d'abord puis en int
    except ValueError:
        #print(f"❌ Erreur : Impossible de convertir {value} en int")
        return 0  # Retourne None en cas d'erreur


# ---- PARSING DU FICHIER XML ----
root = tree.getroot()

print("Début du traitement")

start_time = time.time()  # ⏱ Début du chrono

for pdv in root.findall("pdv"):
    # Récupération des informations
    pdv_id = int(pdv.get("id", 0))
    latitude = safe_int(pdv.get("latitude")) / 100000
    longitude = safe_int(pdv.get("longitude")) / 100000
    cp = pdv.get("cp", "")
    pop = pdv.get("pop", "")
    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 ""

    # Insertion des prix
    for prix in pdv.findall("prix"):
        try:
            carburant_nom = prix.get("nom")
            prix_valeur = float(prix.get("valeur"))
            modified_at = prix.get("maj")
            rupture = 0

            cursor.execute("""
                UPDATE carburantlist
                SET price = %s, modified_at = %s, rupture = 0
                WHERE station_id = ( 
                    SELECT id FROM station WHERE id_station = %s 
                ) AND carburant_id = ( 
                    SELECT id FROM carburant WHERE alias = %s 
                )
            """, ( prix_valeur, modified_at, pdv_id, carburant_nom ))
            conn.commit()

        except mysql.connector.Error as e:
            print(f"Erreur lors de l'insertion du carburant '{carburant_nom}' pour la station {pdv_id}: {e}")


end_time = time.time()  # ⏱ Fin du chrono
elapsed_time = end_time - start_time  # ⏱ Calcul du temps

print(f"✅ Prix insérés avec succès en {elapsed_time:.2f}s !")

start_time = time.time()  # ⏱ Début du chrono

for pdv in root.findall("pdv"):
    # Récupération des informations
    pdv_id = int(pdv.get("id", 0))
    latitude = safe_int(pdv.get("latitude")) / 100000
    longitude = safe_int(pdv.get("longitude")) / 100000
    cp = pdv.get("cp", "")
    pop = pdv.get("pop", "")
    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 ""

    # Insertion des ruptures
    for rupture in pdv.findall("rupture"):
        try:
            carburant_nom = rupture.get("nom")  # Corrigé
            modified_at = rupture.get("debut")  # Corrigé

            cursor.execute("""
                UPDATE carburantlist 
                SET rupture = 1, modified_at = %s
                WHERE station_id = ( 
                    SELECT id FROM station WHERE id_station = %s
                ) AND carburant_id = ( 
                    SELECT id FROM carburant WHERE alias = %s 
                )
            """, (modified_at, pdv_id, carburant_nom))

            conn.commit()
        
        except mysql.connector.Error as e:
            print(f"Erreur lors de l'insertion de la rupture du carburant '{carburant_nom}' pour la station {pdv_id}: {e}")

# ---- COMMIT ET FERMETURE ----

cursor.close()
conn.close()

end_time = time.time()  # ⏱ Fin du chrono
elapsed_time = end_time - start_time  # ⏱ Calcul du temps

print(f"✅ Ruptures insérées avec succès en {elapsed_time:.2f}s !")