import time
import subprocess
from batch_utils import charger_status, sauvegarder_status, JOBS_DIR


while True:
    status = charger_status()
    jobs = [(login, data) for login, data in status.items() if data["status"] == "en attente"]
    jobs = sorted(jobs, key=lambda x: x[1].get("timestamp", 0))

    for i, (login, data) in enumerate(jobs):
        status[login]["position"] = i
        sauvegarder_status(status)

    if jobs:
        login, _ = jobs[0]
        dot_file = JOBS_DIR / f"{login}.dot"
        result_file = JOBS_DIR / f"{login}.zip"

        status[login]["status"] = "en cours"
        sauvegarder_status(status)

        try:
            subprocess.run(["python3", "analyse_ia.py", str(dot_file), str(result_file)], check=True)
            status[login]["status"] = "terminé"
        except Exception as e:
            status[login]["status"] = "échoué"
            status[login]["error"] = str(e)

        sauvegarder_status(status)

    time.sleep(60)
