"""The GAIA agent: a small ReAct loop over the tools in :mod:`gaia_agent.tools`.

The loop is text based instead of using native function calling because the
default backend is a small local model; a single strict JSON reply per turn is
easier to validate and repair than provider specific tool-call payloads.
"""

from __future__ import annotations

import json
import re
import time
from dataclasses import dataclass, field
from pathlib import Path

from .llm import BaseLLM, build_llm
from .tools import TaskContext, build_registry, execute, parse_tool_input, render_tool_list

SYSTEM_PROMPT = """You are a careful research agent solving GAIA benchmark questions.

Work step by step and use the tools to find facts. Never invent facts, URLs or numbers.

Available tools:
{tools}

Reply with EXACTLY ONE JSON object per turn, nothing else before or after it.

To use a tool:
{{"thought": "<one short sentence>", "tool": "<tool name>", "input": {{"<argument>": "<value>"}}}}

To give the final answer:
{{"thought": "<one short sentence>", "answer": "<the literal answer>"}}

Rules for the final answer:
- It is compared to the expected answer as an exact string, so keep it minimal: a name, a number, a date, or a comma separated list. No sentences, no units, no quotes, no "FINAL ANSWER:" prefix.
- Follow every formatting instruction in the question literally (order, alphabetisation, number formats, "last names only", IOC codes, ...).
- For comma separated lists use ", " as the separator and no trailing period.
- Counting questions: list the qualifying items and their years in your thought, then count them. Never guess a count.
- Call read_attachment before answering any question that refers to an attached file.
- Be efficient: you have at most {max_steps} steps, and one tool call per step.
"""

# A single worked example anchors the output format for small models.
FEW_SHOT = [
    {"role": "user", "content": "Which city is the birthplace of the author of 'The Trial'?"},
    {
        "role": "assistant",
        "content": '{"thought": "I need to identify the author and his birthplace.", "tool": "wikipedia", "input": {"query": "The Trial Franz Kafka"}}',
    },
    {
        "role": "user",
        "content": "Observation from wikipedia:\n# The Trial\nThe Trial is a novel written by Franz Kafka, born in Prague.",
    },
    {
        "role": "assistant",
        "content": '{"thought": "Kafka was born in Prague, which answers the question.", "answer": "Prague"}',
    },
]

FORMAT_PROMPT = """You check the formatting of a final answer for an exact-match grader.

Question:
{question}

Draft answer:
{draft}

Rewrite the answer so that it satisfies every formatting instruction in the question
(ordering, alphabetisation, list separators, requested unit or code, "only names", ...).
Do not add explanations. Reply with this JSON only:
{{"answer": "<final answer string>"}}"""


@dataclass
class AgentResult:
    answer: str
    steps: list[dict] = field(default_factory=list)
    elapsed: float = 0.0
    transcript: str = ""


def extract_json(text: str) -> dict | None:
    """Pull the first JSON object out of a model reply."""
    if not text:
        return None
    cleaned = text.strip()
    cleaned = re.sub(r"^```(?:json)?|```$", "", cleaned, flags=re.MULTILINE).strip()
    decoder = json.JSONDecoder()
    for index, char in enumerate(cleaned):
        if char != "{":
            continue
        try:
            payload, _ = decoder.raw_decode(cleaned[index:])
        except json.JSONDecodeError:
            continue
        if isinstance(payload, dict):
            return payload
    return None


def clean_answer(text: str) -> str:
    """Normalise a model produced answer into something an exact match grader accepts."""
    answer = (text or "").strip()
    if not answer:
        return ""

    answer = re.sub(r"^```[a-zA-Z]*\s*|\s*```$", "", answer, flags=re.MULTILINE).strip()
    match = re.search(r"final answer\s*[:\-]\s*(.+)", answer, re.IGNORECASE | re.DOTALL)
    if match:
        answer = match.group(1).strip()
    answer = re.sub(r"^(?:the\s+)?answer\s*(?:is|:)\s*", "", answer, flags=re.IGNORECASE).strip()

    if "\n" in answer:
        lines = [line.strip() for line in answer.splitlines() if line.strip()]
        answer = lines[-1] if lines else answer

    answer = answer.strip().strip("\"'`*").strip()
    answer = answer.rstrip(".")
    return answer.strip()


class GaiaAgent:
    """Runs one question end to end."""

    def __init__(self, llm: BaseLLM | None = None, max_steps: int = 7, verbose: bool = True):
        self.llm = llm or build_llm()
        self.max_steps = max_steps
        self.verbose = verbose

    def _log(self, message: str) -> None:
        if self.verbose:
            print(message, flush=True)

    def answer_question(
        self,
        question: str,
        task_id: str = "",
        file_name: str = "",
        artifact: Path | None = None,
        workdir: Path | None = None,
    ) -> AgentResult:
        started = time.time()
        ctx = TaskContext(
            task_id=task_id or "local",
            question=question,
            file_name=file_name or "",
            workdir=Path(workdir or Path.cwd()),
            artifact=Path(artifact) if artifact else None,
        )
        registry = build_registry(ctx)
        system = {
            "role": "system",
            "content": SYSTEM_PROMPT.format(tools=render_tool_list(registry), max_steps=self.max_steps),
        }
        messages = [system, *FEW_SHOT, {"role": "user", "content": self._user_prompt(ctx)}]
        steps: list[dict] = []
        answer = ""

        for step in range(1, self.max_steps + 1):
            reply = self.llm.chat(messages, max_tokens=700)
            action = extract_json(reply)
            messages.append({"role": "assistant", "content": reply})

            if action is None:
                self._log(f"  [{step}] unparsable reply, asking for JSON again")
                messages.append(
                    {
                        "role": "user",
                        "content": 'Your reply was not valid JSON. Reply with one JSON object only, '
                        'either {"tool": ..., "input": ...} or {"answer": ...}.',
                    }
                )
                continue

            if "answer" in action and str(action.get("answer", "")).strip():
                answer = str(action["answer"])
                steps.append({"step": step, "type": "answer", "value": clean_answer(answer)})
                self._log(f"  [{step}] answer: {clean_answer(answer)!r}")
                break

            tool_name = str(action.get("tool", "")).strip()
            if tool_name not in registry:
                messages.append(
                    {
                        "role": "user",
                        "content": f'Unknown tool "{tool_name}". Use one of: {", ".join(registry)}.',
                    }
                )
                continue

            arguments = parse_tool_input(action.get("input", action.get("arguments")))
            self._log(f"  [{step}] tool {tool_name}({json.dumps(arguments)[:120]})")
            observation = execute(registry[tool_name], arguments)
            steps.append(
                {
                    "step": step,
                    "type": "tool",
                    "tool": tool_name,
                    "input": arguments,
                    "observation": observation[:600],
                }
            )
            self._log(f"      -> {observation[:200].replace(chr(10), ' ')}")
            messages.append({"role": "user", "content": f"Observation from {tool_name}:\n{observation}"})

        if not answer:
            answer = self._force_answer(messages)
            steps.append({"step": self.max_steps, "type": "forced", "value": answer})

        final = self._reformat(messages, question, answer)
        answer = clean_answer(final) or clean_answer(answer)
        return AgentResult(
            answer=answer,
            steps=steps,
            elapsed=time.time() - started,
            transcript="\n".join(m.get("content", "") for m in messages),
        )

    # ------------------------------------------------------------------ #
    def _user_prompt(self, ctx: TaskContext) -> str:
        lines = [f"Question:\n{ctx.question}"]
        if ctx.artifact:
            lines.append(
                f"\nAn attached file is available: {ctx.file_name} "
                f"(type {ctx.artifact_suffix}). Use the tools to read it."
            )
        return "\n".join(lines)

    def _force_answer(self, messages: list[dict]) -> str:
        """Ask for a best effort answer when the step budget is exhausted."""
        self._log("  [force] step budget reached, requesting best answer")
        prompt = {
            "role": "user",
            "content": "Stop researching. Based on what you found, reply with the JSON "
            '{"thought": "...", "answer": "<literal answer>"} only.',
        }
        reply = self.llm.chat([*messages, prompt], max_tokens=300)
        action = extract_json(reply)
        if action and str(action.get("answer", "")).strip():
            return str(action["answer"])
        return reply

    def _reformat(self, messages: list[dict], question: str, answer: str) -> str:
        """One cheap verification pass that enforces the requested answer format."""
        draft = clean_answer(answer)
        if not draft:
            return draft
        prompt = FORMAT_PROMPT.format(question=question, draft=draft)
        try:
            reply = self.llm.chat([{"role": "user", "content": prompt}], max_tokens=200)
        except Exception as exc:
            self._log(f"  [format] skipped ({exc})")
            return draft
        action = extract_json(reply)
        if action and str(action.get("answer", "")).strip():
            formatted = clean_answer(str(action["answer"]))
            if formatted:
                if formatted != draft:
                    self._log(f"  [format] {draft!r} -> {formatted!r}")
                return formatted
        return draft


class BasicAgent:
    """Drop-in replacement for the template agent: a callable question -> answer."""

    def __init__(self, max_steps: int = 7, verbose: bool = True):
        self.agent = GaiaAgent(max_steps=max_steps, verbose=verbose)
        self.llm = self.agent.llm

    def __call__(self, question: str, task_id: str = "", file_name: str = "", artifact: Path | None = None) -> str:
        result = self.agent.answer_question(
            question, task_id=task_id, file_name=file_name, artifact=artifact
        )
        return result.answer
