"""The agent loop.

This is the whole idea of agentic AI in about two hundred lines: call the model,
see whether it asked for a tool, run the tool, append the result, call again,
stop when it answers or when a budget runs out.

Everything a framework gives you is a variation on this. Writing it once by hand
is why the rest of the course makes sense.

The part beginners omit, and the reason their agents burn money in production,
is the *budget*. A loop with no ceiling is not an agent, it is an unbounded
while-loop with a credit card attached.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable

from .model import Completion, Message, Model
from .tools import FatalToolError, Registry, ToolResult
from .trace import NullTracer, Tracer


class Stop(str, Enum):
    """Why a run ended. Every terminal state is named - there is no 'just fell out'."""

    ANSWERED = "answered"
    STEP_BUDGET = "step_budget_exhausted"
    TOKEN_BUDGET = "token_budget_exhausted"
    COST_BUDGET = "cost_budget_exhausted"
    REPEATED_CALL = "repeated_identical_call"
    TOOL_FATAL = "fatal_tool_error"
    NO_PROGRESS = "no_progress"


@dataclass
class Budget:
    """Ceilings for one run. All of them are load-bearing.

    max_steps      - model calls. The primary guard.
    max_tokens     - cumulative input+output across the run.
    max_cost       - in whatever unit `price_per_1k` uses.
    repeat_limit   - identical (name, arguments) calls tolerated before stopping.
    """

    max_steps: int = 8
    max_tokens: int | None = None
    max_cost: float | None = None
    repeat_limit: int = 2
    price_per_1k_input: float = 0.0
    price_per_1k_output: float = 0.0

    def cost_of(self, input_tokens: int, output_tokens: int) -> float:
        return (
            input_tokens / 1000 * self.price_per_1k_input
            + output_tokens / 1000 * self.price_per_1k_output
        )


@dataclass
class Step:
    """One turn of the loop, kept for inspection and trajectory evals.

    Requested and executed are deliberately separate. A tool the model asked for
    and the registry refused did NOT run, and conflating the two makes a working
    guardrail look like a breach - see `Run.trajectory`.
    """

    index: int
    completion: Completion
    tool_results: list[ToolResult] = field(default_factory=list)

    @property
    def requested_names(self) -> list[str]:
        """What the model asked for, including calls that were denied."""
        return [tc.name for tc in self.completion.tool_calls]

    @property
    def succeeded_names(self) -> list[str]:
        """What actually ran and returned successfully."""
        return [r.name for r in self.tool_results if r.ok]

    @property
    def blocked_names(self) -> list[str]:
        """Requested but denied, invalid, or failed - nothing happened."""
        return [r.name for r in self.tool_results if not r.ok]


@dataclass
class Run:
    """The outcome of one agent run."""

    output: str
    stop: Stop
    steps: list[Step] = field(default_factory=list)
    messages: list[Message] = field(default_factory=list)
    input_tokens: int = 0
    output_tokens: int = 0
    cost: float = 0.0
    tracer: Tracer | None = None

    @property
    def ok(self) -> bool:
        return self.stop is Stop.ANSWERED

    @property
    def step_count(self) -> int:
        return len(self.steps)

    def trajectory(self) -> list[str]:
        """Tools that actually RAN, in order. The unit trajectory evals score.

        Successful executions only. A call the registry denied is not part of the
        trajectory, because nothing happened - asserting `never_used("refund")`
        must PASS when a guardrail blocks an injected refund attempt, otherwise
        the eval punishes the defense for working.
        """
        return [name for s in self.steps for name in s.succeeded_names]

    def requested_tools(self) -> list[str]:
        """Tools the model ASKED for, including denied ones.

        This is the security signal: it tells you an injection got far enough to
        make the model try, even though the attempt was contained.
        """
        return [name for s in self.steps for name in s.requested_names]

    def blocked_tools(self) -> list[str]:
        """Requested but not executed - denied, invalid, or failed."""
        return [name for s in self.steps for name in s.blocked_names]

    def used_tool(self, name: str) -> bool:
        """True only if the tool actually ran successfully."""
        return name in self.trajectory()

    def requested_tool(self, name: str) -> bool:
        return name in self.requested_tools()


class Agent:
    """A minimal, budgeted, traced ReAct-style agent.

        agent = Agent(model, registry, system="You are a support agent.")
        run = agent.run("Where is order 4471?")

    `run` always returns; it does not raise on budget exhaustion. A caller has
    to look at `run.stop`, which is deliberate: silent truncation is the failure
    mode this design is built to prevent.
    """

    def __init__(
        self,
        model: Model,
        registry: Registry | None = None,
        system: str = "",
        budget: Budget | None = None,
        tracer: Tracer | None = None,
        max_output_tokens: int = 512,
        temperature: float = 0.0,
        on_step: Callable[[Step], None] | None = None,
    ) -> None:
        self.model = model
        self.registry = registry or Registry()
        self.system = system
        self.budget = budget or Budget()
        self.tracer = tracer or NullTracer()
        self.max_output_tokens = max_output_tokens
        self.temperature = temperature
        self.on_step = on_step

    # ------------------------------------------------------------------

    def run(self, task: str, history: list[Message] | None = None) -> Run:
        messages: list[Message] = []
        if self.system:
            messages.append(Message(role="system", content=self.system))
        messages.extend(history or [])
        messages.append(Message(role="user", content=task))

        steps: list[Step] = []
        seen_calls: dict[tuple[str, str], int] = {}
        in_tok = out_tok = 0
        cost = 0.0

        with self.tracer.span("agent.run", "run", task=task) as run_span:
            for i in range(self.budget.max_steps):
                # -- model call -------------------------------------------------
                with self.tracer.span(f"model.call.{i}", "model") as m_span:
                    completion = self.model.complete(
                        messages,
                        tools=self.registry.schemas() or None,
                        max_output_tokens=self.max_output_tokens,
                        temperature=self.temperature,
                    )
                    step_cost = self.budget.cost_of(
                        completion.input_tokens, completion.output_tokens
                    )
                    m_span.set(
                        model=completion.model,
                        finish_reason=completion.finish_reason,
                        input_tokens=completion.input_tokens,
                        output_tokens=completion.output_tokens,
                        cost=step_cost,
                        requested_tools=[tc.name for tc in completion.tool_calls],
                    )

                in_tok += completion.input_tokens
                out_tok += completion.output_tokens
                cost += step_cost

                step = Step(index=i, completion=completion)
                steps.append(step)
                messages.append(completion.as_message())

                # -- terminal: the model answered ------------------------------
                if not completion.wants_tools:
                    if self.on_step:
                        self.on_step(step)
                    run_span.set(stop=Stop.ANSWERED.value, steps=len(steps))
                    return self._finish(
                        completion.text, Stop.ANSWERED, steps, messages, in_tok, out_tok, cost
                    )

                # -- loop detection -------------------------------------------
                # An agent that calls the same tool with the same arguments over
                # and over is stuck, not working. Catching it here is cheaper
                # than catching it on the bill.
                for tc in completion.tool_calls:
                    key = (tc.name, _stable(tc.arguments))
                    seen_calls[key] = seen_calls.get(key, 0) + 1
                    if seen_calls[key] > self.budget.repeat_limit:
                        run_span.set(stop=Stop.REPEATED_CALL.value)
                        return self._finish(
                            f"Stopped: repeated the same {tc.name} call "
                            f"{seen_calls[key]} times without progress.",
                            Stop.REPEATED_CALL,
                            steps, messages, in_tok, out_tok, cost,
                        )

                # -- run the tools --------------------------------------------
                for tc in completion.tool_calls:
                    with self.tracer.span(f"tool.{tc.name}", "tool", arguments=tc.arguments) as t_span:
                        try:
                            result = self.registry.dispatch(tc)
                        except FatalToolError as exc:
                            t_span.error = f"FatalToolError: {exc}"
                            run_span.set(stop=Stop.TOOL_FATAL.value)
                            return self._finish(
                                "Stopped: the run hit an unrecoverable tool error.",
                                Stop.TOOL_FATAL,
                                steps, messages, in_tok, out_tok, cost,
                            )
                        t_span.set(ok=result.ok, duration_ms=result.duration_ms)

                    step.tool_results.append(result)
                    messages.append(result.as_message())

                if self.on_step:
                    self.on_step(step)

                # -- budgets ---------------------------------------------------
                if self.budget.max_tokens is not None and in_tok + out_tok >= self.budget.max_tokens:
                    run_span.set(stop=Stop.TOKEN_BUDGET.value)
                    return self._finish(
                        "Stopped: token budget exhausted before reaching an answer.",
                        Stop.TOKEN_BUDGET, steps, messages, in_tok, out_tok, cost,
                    )
                if self.budget.max_cost is not None and cost >= self.budget.max_cost:
                    run_span.set(stop=Stop.COST_BUDGET.value)
                    return self._finish(
                        "Stopped: cost budget exhausted before reaching an answer.",
                        Stop.COST_BUDGET, steps, messages, in_tok, out_tok, cost,
                    )

            run_span.set(stop=Stop.STEP_BUDGET.value, steps=len(steps))
            return self._finish(
                f"Stopped: reached the {self.budget.max_steps}-step limit without "
                f"an answer.",
                Stop.STEP_BUDGET, steps, messages, in_tok, out_tok, cost,
            )

    # ------------------------------------------------------------------

    def _finish(
        self,
        output: str,
        stop: Stop,
        steps: list[Step],
        messages: list[Message],
        in_tok: int,
        out_tok: int,
        cost: float,
    ) -> Run:
        return Run(
            output=output,
            stop=stop,
            steps=steps,
            messages=messages,
            input_tokens=in_tok,
            output_tokens=out_tok,
            cost=cost,
            tracer=self.tracer if not isinstance(self.tracer, NullTracer) else None,
        )


def _stable(d: dict[str, Any]) -> str:
    import json

    return json.dumps(d, sort_keys=True, default=str)