"""Access to the course evaluation API and the task artifacts."""

from __future__ import annotations

import json
import os
from pathlib import Path

import requests

DEFAULT_API_URL = os.getenv("GAIA_API_URL", "https://agents-course-unit4-scoring.hf.space")

# The scoring API occasionally ships without the task files mapped (GET /files 404).
# This public mirror of the same GAIA validation split is used as a fallback so the
# agent can still read the attachments that belong to the questions.
ARTIFACT_MIRROR = os.getenv(
    "GAIA_ARTIFACT_MIRROR",
    "https://huggingface.co/datasets/evatan/GAIA/resolve/main/2023/validation",
)

DEFAULT_ARTIFACT_DIR = Path(os.getenv("GAIA_ARTIFACT_DIR", "artifacts"))


def fetch_questions(api_url: str = DEFAULT_API_URL) -> list[dict]:
    """Return the evaluation questions as ``[{task_id, question, Level, file_name}]``."""
    response = requests.get(f"{api_url}/questions", timeout=30)
    response.raise_for_status()
    questions = response.json()
    if not isinstance(questions, list) or not questions:
        raise RuntimeError("The questions endpoint returned an empty or invalid payload")
    return questions


def ensure_artifact(task: dict, artifact_dir: Path = DEFAULT_ARTIFACT_DIR, api_url: str = DEFAULT_API_URL) -> Path | None:
    """Download (once) the file attached to ``task`` and return its local path."""
    file_name = (task.get("file_name") or "").strip()
    if not file_name:
        return None

    artifact_dir = Path(artifact_dir)
    artifact_dir.mkdir(parents=True, exist_ok=True)
    target = artifact_dir / file_name
    if target.exists() and target.stat().st_size > 0:
        return target

    sources = [
        f"{api_url}/files/{task['task_id']}",
        f"{ARTIFACT_MIRROR}/{file_name}",
    ]
    for url in sources:
        try:
            response = requests.get(url, timeout=120)
        except requests.RequestException as exc:
            print(f"[artifact] {file_name}: {exc}")
            continue
        if response.status_code == 200 and response.content:
            target.write_bytes(response.content)
            print(f"[artifact] {file_name} <- {url.split('/')[2]} ({len(response.content)} bytes)")
            return target
    print(f"[artifact] could not download {file_name}")
    return None


def submit_answers(
    answers: list[dict],
    username: str,
    agent_code: str,
    api_url: str = DEFAULT_API_URL,
) -> dict:
    """POST the answers to /submit and return the parsed result."""
    payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers}
    response = requests.post(f"{api_url}/submit", json=payload, timeout=300)
    if response.status_code >= 400:
        detail = response.text[:500]
        try:
            detail = response.json().get("detail", detail)
        except (json.JSONDecodeError, ValueError):
            pass
        raise RuntimeError(f"submission failed with HTTP {response.status_code}: {detail}")
    return response.json()
