"""The model boundary.

Everything in this course talks to a model through `Model.complete`. That one
seam is why the whole course is testable offline: `FakeModel` is scripted and
deterministic, so an agent loop, an eval suite, and a trace all behave
identically whether a real provider is on the other end or not.

Run the tests with no API key and no pip install:

    python3 -m unittest discover -s tests -t .
"""

from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable, Protocol


# --------------------------------------------------------------------------
# Messages
# --------------------------------------------------------------------------

# Roles follow the shape every major provider converged on. `tool` carries the
# result of a tool the model asked for, matched back by call id.
ROLES = ("system", "user", "assistant", "tool")


@dataclass(frozen=True)
class Message:
    role: str
    content: str = ""
    # Set when the assistant is requesting tool calls rather than replying.
    tool_calls: tuple["ToolCall", ...] = ()
    # Set on role="tool" to match a result back to its request.
    tool_call_id: str | None = None

    def __post_init__(self) -> None:
        if self.role not in ROLES:
            raise ValueError(f"unknown role {self.role!r}, expected one of {ROLES}")

    def to_dict(self) -> dict[str, Any]:
        d: dict[str, Any] = {"role": self.role, "content": self.content}
        if self.tool_calls:
            d["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
        if self.tool_call_id:
            d["tool_call_id"] = self.tool_call_id
        return d


@dataclass(frozen=True)
class ToolCall:
    """A model's *request* to run a tool. The model never executes anything."""

    id: str
    name: str
    arguments: dict[str, Any]

    def to_dict(self) -> dict[str, Any]:
        return {"id": self.id, "name": self.name, "arguments": self.arguments}


@dataclass
class Completion:
    text: str = ""
    tool_calls: tuple[ToolCall, ...] = ()
    # finish_reason is "stop" for a normal reply, "tool_calls" when the model
    # wants a tool run, "length" when it hit the output cap.
    finish_reason: str = "stop"
    input_tokens: int = 0
    output_tokens: int = 0
    model: str = "fake"

    @property
    def wants_tools(self) -> bool:
        return bool(self.tool_calls)

    def as_message(self) -> Message:
        return Message(
            role="assistant", content=self.text, tool_calls=self.tool_calls
        )


# --------------------------------------------------------------------------
# The seam
# --------------------------------------------------------------------------


class Model(Protocol):
    """The only thing the rest of the course depends on."""

    def complete(
        self,
        messages: list[Message],
        tools: list[dict[str, Any]] | None = None,
        max_output_tokens: int = 512,
        temperature: float = 0.0,
    ) -> Completion: ...


def estimate_tokens(text: str) -> int:
    """Rough token estimate: ~4 characters per token for English prose.

    Deliberately crude. Lesson 2 explains why you must use the real tokenizer
    for anything that *enforces* a limit, and why an estimate is fine for
    planning. Used here so FakeModel can report plausible usage offline.
    """
    return max(1, len(text) // 4)


# --------------------------------------------------------------------------
# FakeModel - the reason this course runs offline
# --------------------------------------------------------------------------

# A scripted reply: either literal text, a tool request, or a callable that
# inspects the conversation and decides. Callables are what let you fake a
# model that "reasons" - e.g. call the search tool, then answer from its result.
Reply = str | Completion | Callable[[list[Message]], "str | Completion"]


class FakeModel:
    """A deterministic, scripted stand-in for a real model.

    Two ways to use it:

    1. Scripted queue - hand it replies in order. Good for testing one path.

           m = FakeModel(["hello"])

    2. Callable replies - decide based on the conversation so far. Good for
       testing an agent loop that must react to a tool result.

           def reply(msgs):
               if not any(m.role == "tool" for m in msgs):
                   return tool_call("search", {"q": "cats"})
               return "Found it."

           m = FakeModel([reply])

    It records every call, so tests can assert on what the agent actually sent -
    which is how you catch an agent that silently drops history or forgets to
    append a tool result.
    """

    def __init__(self, replies: Iterable[Reply] | None = None, name: str = "fake") -> None:
        self._replies: list[Reply] = list(replies or [])
        self.name = name
        self.calls: list[dict[str, Any]] = []

    # -- scripting ------------------------------------------------------

    def queue(self, *replies: Reply) -> "FakeModel":
        self._replies.extend(replies)
        return self

    @property
    def call_count(self) -> int:
        return len(self.calls)

    def last_messages(self) -> list[Message]:
        if not self.calls:
            raise AssertionError("model was never called")
        return self.calls[-1]["messages"]

    # -- the Model protocol --------------------------------------------

    def complete(
        self,
        messages: list[Message],
        tools: list[dict[str, Any]] | None = None,
        max_output_tokens: int = 512,
        temperature: float = 0.0,
    ) -> Completion:
        self.calls.append(
            {
                "messages": list(messages),
                "tools": list(tools or []),
                "max_output_tokens": max_output_tokens,
                "temperature": temperature,
            }
        )

        if not self._replies:
            # Running dry is almost always a test bug - the agent looped more
            # times than you scripted. Say so loudly rather than returning "".
            raise AssertionError(
                f"FakeModel ran out of scripted replies on call "
                f"{len(self.calls)}. Queue more, or check why the agent "
                f"looped further than expected."
            )

        reply = self._replies.pop(0)
        if callable(reply):
            reply = reply(list(messages))

        completion = reply if isinstance(reply, Completion) else Completion(text=str(reply))
        completion.model = self.name
        completion.input_tokens = sum(estimate_tokens(m.content) for m in messages)
        completion.output_tokens = estimate_tokens(completion.text)
        if completion.tool_calls and completion.finish_reason == "stop":
            completion.finish_reason = "tool_calls"
        return completion


# -- helpers for writing scripted replies ------------------------------


_call_counter = 0


def tool_call(name: str, arguments: dict[str, Any], call_id: str | None = None) -> Completion:
    """Script a model turn that requests one tool."""
    global _call_counter
    if call_id is None:
        _call_counter += 1
        call_id = f"call_{_call_counter}"
    return Completion(
        tool_calls=(ToolCall(id=call_id, name=name, arguments=arguments),),
        finish_reason="tool_calls",
    )


def tool_calls(*specs: tuple[str, dict[str, Any]]) -> Completion:
    """Script a model turn that requests several tools in parallel."""
    global _call_counter
    calls = []
    for name, args in specs:
        _call_counter += 1
        calls.append(ToolCall(id=f"call_{_call_counter}", name=name, arguments=args))
    return Completion(tool_calls=tuple(calls), finish_reason="tool_calls")


def reset_call_ids() -> None:
    """Make call ids reproducible across tests."""
    global _call_counter
    _call_counter = 0


def echo_json(payload: Any) -> Completion:
    """Script a model turn that returns JSON - for structured-output lessons."""
    return Completion(text=json.dumps(payload))


# --------------------------------------------------------------------------
# Real providers
# --------------------------------------------------------------------------


@dataclass
class RetryPolicy:
    attempts: int = 3
    base_delay: float = 0.5
    max_delay: float = 8.0


class HTTPModel:
    """Minimal real-provider adapter, stdlib only.

    Deliberately thin. The course teaches the loop, not an SDK, and a thin
    adapter is exactly the "narrow interface" argued for in the model-selection
    lesson - small enough that a second provider is an afternoon's work.

    Subclass and implement `_build_body` / `_parse` for a given provider. The
    course ships no provider defaults on purpose: endpoints and field names
    move, and a hardcoded one would rot. See lessons/README.md for a worked
    adapter you can paste your provider's shape into.
    """

    def __init__(
        self,
        endpoint: str,
        api_key: str,
        model: str,
        timeout: float = 30.0,
        retry: RetryPolicy | None = None,
    ) -> None:
        if not api_key:
            raise ValueError("api_key is required for HTTPModel; use FakeModel offline")
        self.endpoint = endpoint
        self._api_key = api_key
        self.model = model
        self.timeout = timeout
        self.retry = retry or RetryPolicy()

    # Subclasses override these two.
    def _build_body(
        self,
        messages: list[Message],
        tools: list[dict[str, Any]] | None,
        max_output_tokens: int,
        temperature: float,
    ) -> dict[str, Any]:
        return {
            "model": self.model,
            "messages": [m.to_dict() for m in messages],
            "max_tokens": max_output_tokens,
            "temperature": temperature,
            **({"tools": tools} if tools else {}),
        }

    def _parse(self, payload: dict[str, Any]) -> Completion:
        raise NotImplementedError(
            "Implement _parse for your provider - see lessons/README.md"
        )

    def complete(
        self,
        messages: list[Message],
        tools: list[dict[str, Any]] | None = None,
        max_output_tokens: int = 512,
        temperature: float = 0.0,
    ) -> Completion:
        import time
        import urllib.error
        import urllib.request

        body = json.dumps(
            self._build_body(messages, tools, max_output_tokens, temperature)
        ).encode()

        delay = self.retry.base_delay
        last_error: Exception | None = None

        for attempt in range(self.retry.attempts):
            req = urllib.request.Request(
                self.endpoint,
                data=body,
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {self._api_key}",
                },
                method="POST",
            )
            try:
                with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                    return self._parse(json.loads(resp.read()))
            except urllib.error.HTTPError as exc:
                # 4xx other than 429 will fail identically forever - do not retry.
                if exc.code != 429 and 400 <= exc.code < 500:
                    raise
                last_error = exc
            except (urllib.error.URLError, TimeoutError) as exc:
                last_error = exc

            if attempt < self.retry.attempts - 1:
                # Full jitter. Lesson 7 explains why the jitter is not optional.
                import random

                time.sleep(random.uniform(0, min(delay, self.retry.max_delay)))
                delay *= 2

        raise RuntimeError(f"model call failed after {self.retry.attempts} attempts") from last_error