import os
import shutil
import requests
from datetime import datetime

EXPORT_URL = "https://vence-pharmacieposte.fr/modules/ajaxsmartsearch/export_labos.php"
LABOS_JSON_URL = "https://vence-pharmacieposte.fr/labos.json"
PYTHON_LABOS = "/home/xema2934/xema2934.odns.fr/xema2934.odns.fr/labos.json"
BACKUP_DIR = "/home/xema2934/xema2934.odns.fr/xema2934.odns.fr/labos_backups/"

os.makedirs(BACKUP_DIR, exist_ok=True)

def backup_file(filepath):
    if os.path.isfile(filepath):
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        base = os.path.basename(filepath)
        backup_path = os.path.join(BACKUP_DIR, f"{base}.{timestamp}.bak")
        shutil.copy2(filepath, backup_path)
        print(f"[{datetime.now()}] Backup créé : {backup_path}")

def sync_labos_json():
    try:
        # 1. Déclencher l'export PHP via HTTP
        from requests.auth import HTTPBasicAuth
        r = requests.get(EXPORT_URL, auth=HTTPBasicAuth('admin', 'totototo'), timeout=30)
        if r.status_code != 200:
            print(f"[{datetime.now()}] ERREUR HTTP export_labos.php : statut {r.status_code}")
            return
        print(f"[{datetime.now()}] export_labos.php appelé via HTTP.")

        # 2. Télécharger le nouveau labos.json
        r = requests.get(LABOS_JSON_URL, auth=HTTPBasicAuth('admin', 'totototo'), timeout=30)
        if r.status_code != 200:
            print(f"[{datetime.now()}] ERREUR HTTP labos.json : statut {r.status_code}")
            return
        # Vérifier que le JSON est valide
        try:
            json_content = r.json()
            assert isinstance(json_content, list)
        except Exception as e:
            print(f"[{datetime.now()}] ERREUR : labos.json téléchargé invalide : {e}")
            return

        # 3. Sauvegarder l'ancien fichier (version horodatée)
        backup_file(PYTHON_LABOS)

        # 4. Écrire le nouveau fichier
        with open(PYTHON_LABOS, "w", encoding="utf-8") as f:
            f.write(r.text)
        print(f"[{datetime.now()}] Synchronisation labos.json réussie.")

    except Exception as e:
        print(f"[{datetime.now()}] ERREUR lors de la synchronisation : {e}")
        # Restaurer la dernière sauvegarde horodatée si besoin
        backups = sorted(
            [f for f in os.listdir(BACKUP_DIR) if f.startswith('labos.json')],
            reverse=True
        )
        if backups:
            last_backup = os.path.join(BACKUP_DIR, backups[0])
            shutil.copy2(last_backup, PYTHON_LABOS)
            print(f"[{datetime.now()}] Dernière sauvegarde restaurée : {last_backup}")

if __name__ == "__main__":
    sync_labos_json()
