"""GAIA Final Assignment - Gradio entry point.

The template only returned a fixed string. This version runs a real agent
(defined in the ``gaia_agent`` package) over every evaluation question, shows
the per question trace and submits the answers to the scoring API.

Login with the Hugging Face button once the Space is public; the username from
the OAuth profile is what ends up on the leaderboard.
"""

import os
import time
import traceback

import gradio as gr
import pandas as pd

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

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
ARTIFACT_DIR = os.getenv("GAIA_ARTIFACT_DIR", str(DEFAULT_ARTIFACT_DIR))

# The agent is expensive to initialise (it may load a local model), so keep one
# instance for the whole Space lifetime.
_AGENT = {"instance": None, "error": None}


def get_agent() -> GaiaAgent:
    if _AGENT["instance"] is None and _AGENT["error"] is None:
        try:
            _AGENT["instance"] = GaiaAgent(llm=build_llm(), max_steps=int(os.getenv("GAIA_MAX_STEPS", "6")))
        except LLMError as exc:
            _AGENT["error"] = str(exc)
            raise
    if _AGENT["error"]:
        raise LLMError(_AGENT["error"])
    return _AGENT["instance"]


def run_and_submit_all(profile: gr.OAuthProfile | None, progress=gr.Progress()):
    """Fetch all questions, answer them with the agent, submit and report the score."""
    space_id = os.getenv("SPACE_ID")
    api_url = os.getenv("GAIA_API_URL", DEFAULT_API_URL)

    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        return "Please log in with the Hugging Face button first.", None

    try:
        agent = get_agent()
    except Exception as exc:
        return f"Agent initialisation failed: {exc}", None

    agent_code = (
        f"https://huggingface.co/spaces/{space_id}/tree/main"
        if space_id
        else "https://huggingface.co/spaces/agents-course/Final_Assignment_Template"
    )

    import requests

    try:
        response = requests.get(f"{api_url}/questions", timeout=30)
        response.raise_for_status()
        questions = response.json()
    except Exception as exc:
        return f"Could not fetch the questions: {exc}", None
    if not questions:
        return "The questions endpoint returned an empty list.", None

    answers_payload = []
    rows = []
    for index, item in enumerate(questions):
        task_id = item.get("task_id")
        question = item.get("question", "")
        if not task_id or not question:
            continue
        progress((index, len(questions)), desc=f"Question {index + 1}/{len(questions)}")
        try:
            artifact = ensure_artifact(item, ARTIFACT_DIR, api_url)
            started = time.time()
            result = agent.answer_question(
                question,
                task_id=task_id,
                file_name=item.get("file_name", ""),
                artifact=artifact,
                workdir=ARTIFACT_DIR,
            )
            answers_payload.append({"task_id": task_id, "submitted_answer": result.answer})
            rows.append(
                {
                    "Task ID": task_id[:8],
                    "Question": question[:120],
                    "Answer": result.answer,
                    "Seconds": round(time.time() - started, 1),
                }
            )
        except Exception as exc:
            print(f"Error on task {task_id}: {exc}")
            traceback.print_exc()
            answers_payload.append({"task_id": task_id, "submitted_answer": ""})
            rows.append({"Task ID": task_id[:8], "Question": question[:120], "Answer": f"ERROR: {exc}", "Seconds": 0})

    if not answers_payload:
        return "The agent did not produce any answers.", pd.DataFrame(rows)

    try:
        result = submit_answers(answers_payload, username, agent_code, api_url)
    except Exception as exc:
        return f"Submission failed: {exc}", pd.DataFrame(rows)

    status = (
        f"Submission successful for {result.get('username', username)}.\n"
        f"Score: {result.get('score', 'n/a')}% "
        f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
        f"Message: {result.get('message', '')}"
    )
    return status, pd.DataFrame(rows)


with gr.Blocks(title="GAIA Agent - Final Assignment") as demo:
    gr.Markdown("# GAIA Agent - Final Assignment")
    gr.Markdown(
        """
        A research agent that answers the 20 GAIA level 1 questions of the course.

        **How it works:** the agent plans, calls tools (web search, page reading, Wikipedia,
        YouTube captions, Python, attachment parsing, audio transcription, image inspection)
        and returns one literal answer per question.

        1. Log in with Hugging Face - the username is used for the leaderboard.
        2. Press the button. The run takes a while: every question needs several model calls.
        """
    )

    gr.LoginButton()

    run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
    status_output = gr.Textbox(label="Run status / submission result", lines=6, interactive=False)
    results_table = gr.DataFrame(label="Question by question results", wrap=True)

    run_button.click(fn=run_and_submit_all, inputs=None, outputs=[status_output, results_table])

if __name__ == "__main__":
    print("-" * 30 + " App starting " + "-" * 30)
    space_host = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID")
    print(f"SPACE_HOST: {space_host or '(local run)'}")
    print(f"SPACE_ID: {space_id_startup or '(local run)'}")
    print("-" * 70)
    demo.launch(debug=True, share=False)
