# uploader.py

from __future__ import annotations

import os
from typing import Optional

import requests

from config import SERVER_URL


def upload_session_zip(zip_path: str, session_id: str) -> bool:
    """
    Envoie le zip de session au serveur.

    Retourne True si HTTP 2xx, False sinon.
    """
    # Si pas configuré sérieusement, on n'upload pas
    if not SERVER_URL or "example.com" in SERVER_URL:
        print("[agent_v0] SERVER_URL non configuré (ou placeholder), upload désactivé.")
        return False

    if not os.path.isfile(zip_path):
        print(f"[agent_v0] ZIP introuvable pour upload : {zip_path}")
        return False

    print(f"[agent_v0] Upload du ZIP {zip_path} vers {SERVER_URL} ...")

    try:
        with open(zip_path, "rb") as f:
            files = {
                "file": (os.path.basename(zip_path), f, "application/zip"),
            }
            data = {
                "session_id": session_id,
            }
            # Timeout plus agressif pour ne pas bloquer
            resp = requests.post(SERVER_URL, files=files, data=data, timeout=5)

        if 200 <= resp.status_code < 300:
            print(f"[agent_v0] Upload réussi (HTTP {resp.status_code}).")
            return True

        print(f"[agent_v0] Upload échoué (HTTP {resp.status_code}). Réponse: {resp.text[:200]}")
        return False

    except Exception as e:
        print(f"[agent_v0] Erreur lors de l'upload : {e}")
        return False
