"""Command line runner for the GAIA evaluation.

Examples:
    python run_eval.py --list
    python run_eval.py --all                  # run every question, cache the answers
    python run_eval.py --task 8e867cd7        # one question (prefix match on task_id)
    python run_eval.py --submit               # submit the cached answers
"""

from __future__ import annotations

import argparse
import json
import sys
import time
from pathlib import Path

from gaia_agent.agent import GaiaAgent
from gaia_agent.data import DEFAULT_ARTIFACT_DIR, ensure_artifact, fetch_questions, submit_answers
from gaia_agent.llm import build_llm

QUESTIONS_CACHE = Path("questions.json")
ANSWERS_CACHE = Path("answers.json")


def load_questions(refresh: bool = False, api_url: str | None = None) -> list[dict]:
    if QUESTIONS_CACHE.exists() and not refresh:
        return json.loads(QUESTIONS_CACHE.read_text())
    kwargs = {"api_url": api_url} if api_url else {}
    questions = fetch_questions(**kwargs)
    QUESTIONS_CACHE.write_text(json.dumps(questions, indent=1))
    return questions


def load_answers() -> dict:
    if ANSWERS_CACHE.exists():
        try:
            return json.loads(ANSWERS_CACHE.read_text())
        except json.JSONDecodeError:
            return {}
    return {}


def save_answers(answers: dict) -> None:
    ANSWERS_CACHE.write_text(json.dumps(answers, indent=1))


def select(questions: list[dict], task_filters: list[str] | None) -> list[dict]:
    if not task_filters:
        return questions
    wanted = [q for q in questions if any(q["task_id"].startswith(prefix) for prefix in task_filters)]
    if not wanted:
        raise SystemExit(f"No question matched {task_filters}")
    return wanted


def main() -> int:
    parser = argparse.ArgumentParser(description="Run the GAIA agent on the course questions.")
    parser.add_argument("--all", action="store_true", help="run every question")
    parser.add_argument("--task", action="append", help="task_id or unique prefix (repeatable)")
    parser.add_argument("--list", action="store_true", help="print the question list and exit")
    parser.add_argument("--submit", action="store_true", help="submit the cached answers")
    parser.add_argument("--username", default=None, help="Hugging Face username for the submission")
    parser.add_argument("--agent-code", default=None, help="public URL of the agent code")
    parser.add_argument("--max-steps", type=int, default=6)
    parser.add_argument("--llm", default=None, help="mlx | openai | hf | pollinations (default: auto)")
    parser.add_argument("--refresh", action="store_true", help="re-run questions that already have an answer")
    parser.add_argument("--refresh-questions", action="store_true", help="re-fetch the question list")
    args = parser.parse_args()

    questions = load_questions(refresh=args.refresh_questions)
    answers = load_answers()

    if args.list:
        for index, question in enumerate(questions, 1):
            cached = answers.get(question["task_id"], {}).get("answer", "")
            print(f"{index:2d}. {question['task_id']}  file={question.get('file_name') or '-':<45} {cached or '-'}")
        return 0

    if args.submit:
        if not answers:
            raise SystemExit("No cached answers to submit; run with --all first.")
        username = args.username or "ThomasThangHong"
        agent_code = args.agent_code or "https://huggingface.co/spaces/agents-course/Final_Assignment_Template"
        payload = [
            {"task_id": task_id, "submitted_answer": entry.get("answer", "")}
            for task_id, entry in answers.items()
        ]
        print(f"Submitting {len(payload)} answers for {username} ...")
        result = submit_answers(payload, username, agent_code)
        print(json.dumps(result, indent=1))
        return 0

    if not (args.all or args.task):
        parser.error("choose --all, --task <id>, --list or --submit")

    targets = select(questions, args.task)
    agent = GaiaAgent(llm=build_llm(args.llm), max_steps=args.max_steps)
    print(f"Running {len(targets)} question(s) with backend '{agent.llm.name}'")

    for index, task in enumerate(targets, 1):
        task_id = task["task_id"]
        if task_id in answers and not args.refresh:
            print(f"[{index}/{len(targets)}] {task_id} already answered, skipping")
            continue

        artifact = ensure_artifact(task, DEFAULT_ARTIFACT_DIR)
        print(f"\n[{index}/{len(targets)}] {task_id}  file={task.get('file_name') or '-'}")
        print(f"Q: {task['question'][:200]}")
        started = time.time()
        try:
            result = agent.answer_question(
                task["question"],
                task_id=task_id,
                file_name=task.get("file_name", ""),
                artifact=artifact,
                workdir=DEFAULT_ARTIFACT_DIR,
            )
            print(f"A: {result.answer!r}  ({result.elapsed:.0f}s, {len(result.steps)} steps)")
            answers[task_id] = {
                "answer": result.answer,
                "question": task["question"],
                "file_name": task.get("file_name", ""),
                "elapsed": round(result.elapsed, 1),
                "steps": result.steps,
            }
        except Exception as exc:
            print(f"!! failed after {time.time() - started:.0f}s: {type(exc).__name__}: {exc}")
            answers[task_id] = {"answer": "", "question": task["question"], "error": str(exc)}
        save_answers(answers)

    answered = sum(1 for task in questions if answers.get(task["task_id"], {}).get("answer"))
    print(f"\nDone. {answered}/{len(questions)} questions have an answer ({ANSWERS_CACHE}).")
    return 0


if __name__ == "__main__":
    sys.exit(main())
