"""Tools: schemas, validation, authorization, dispatch.

The security boundary of an agent lives in this file. The model only ever
*asks* for a tool by name with arguments; this module decides whether that call
is well-formed and permitted, and only then runs it.

Two rules the lessons keep coming back to:

1. Arguments from a model are untrusted input. Validate them like a request
   body, never like a function call from your own code.
2. Authorization belongs to the caller's identity, not the model's choice. If
   the model picks a record id, you still check the *user* may read it.
"""

from __future__ import annotations

import inspect
import json
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Literal, get_args, get_origin


class ToolError(Exception):
    """A failure the model should see and can plausibly correct.

    Raising this returns the message to the model as a tool result, so it can
    retry with better arguments. Use it for bad input, not-found, and validation
    failures.
    """


class FatalToolError(Exception):
    """A RUNTIME failure the model must NOT see and cannot correct.

    Authorization denials and missing credentials. These abort the run with a
    named stop reason instead of handing the model an error it might try to
    route around.
    """


class ToolConfigError(Exception):
    """A PROGRAMMING error in how tools were wired up.

    Deliberately distinct from FatalToolError. A runtime denial is a legitimate
    outcome that the loop turns into `Stop.TOOL_FATAL`; a misconfigured registry
    is a bug that must surface as a crash. Collapsing the two lets you ship an
    agent whose mutating tools can never execute, and only discover it from a
    stop-reason metric weeks later.
    """


# --------------------------------------------------------------------------
# Schema
# --------------------------------------------------------------------------

_PY_TO_JSON = {str: "string", int: "integer", float: "number", bool: "boolean"}


@dataclass
class Param:
    name: str
    type: Any
    description: str
    required: bool = True
    enum: tuple[Any, ...] | None = None

    def to_schema(self) -> dict[str, Any]:
        origin = get_origin(self.type)
        if origin is Literal:
            # Literal["a", "b"] is the ergonomic way to write an enum.
            values = get_args(self.type)
            return {
                "type": _PY_TO_JSON.get(type(values[0]), "string"),
                "enum": list(values),
                "description": self.description,
            }
        schema: dict[str, Any] = {
            "type": _PY_TO_JSON.get(self.type, "string"),
            "description": self.description,
        }
        if self.enum:
            schema["enum"] = list(self.enum)
        return schema


@dataclass
class Tool:
    """A callable the model may request, plus everything needed to gate it."""

    name: str
    description: str
    params: tuple[Param, ...]
    fn: Callable[..., Any]
    # Mutating tools get stricter treatment: they can require confirmation and
    # they must be idempotent to be safe under retry.
    mutating: bool = False
    requires_confirmation: bool = False
    timeout: float = 10.0

    def to_schema(self) -> dict[str, Any]:
        return {
            "type": "function",
            "function": {
                "name": self.name,
                # The description IS prompt text the model reads. A vague one is
                # the single most common cause of wrong tool selection.
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {p.name: p.to_schema() for p in self.params},
                    "required": [p.name for p in self.params if p.required],
                    "additionalProperties": False,
                },
            },
        }

    def validate(self, arguments: dict[str, Any]) -> dict[str, Any]:
        """Check model-supplied arguments. Raises ToolError so the model can fix it."""
        known = {p.name: p for p in self.params}

        unknown = set(arguments) - set(known)
        if unknown:
            raise ToolError(
                f"unknown argument(s) {sorted(unknown)}; allowed: {sorted(known)}"
            )

        cleaned: dict[str, Any] = {}
        for name, param in known.items():
            if name not in arguments:
                if param.required:
                    raise ToolError(f"missing required argument {name!r}")
                continue

            value = arguments[name]
            origin = get_origin(param.type)

            if origin is Literal:
                allowed = get_args(param.type)
                if value not in allowed:
                    raise ToolError(
                        f"argument {name!r} must be one of {list(allowed)}, got {value!r}"
                    )
            elif param.type is float and isinstance(value, int) and not isinstance(value, bool):
                value = float(value)  # models emit 3 where 3.0 is wanted
            elif param.type is bool:
                if not isinstance(value, bool):
                    raise ToolError(f"argument {name!r} must be a boolean, got {value!r}")
            elif param.type in (str, int, float) and not isinstance(value, param.type):
                raise ToolError(
                    f"argument {name!r} must be {param.type.__name__}, got "
                    f"{type(value).__name__} ({value!r})"
                )

            if param.enum and value not in param.enum:
                raise ToolError(
                    f"argument {name!r} must be one of {list(param.enum)}, got {value!r}"
                )

            cleaned[name] = value

        return cleaned


def tool(
    name: str | None = None,
    description: str = "",
    mutating: bool = False,
    requires_confirmation: bool = False,
    timeout: float = 10.0,
    **param_docs: str,
):
    """Decorator that builds a Tool from a typed function.

        @tool(description="Look up an order by id.", order_id="The order id.")
        def get_order(order_id: str) -> dict:
            ...

    Types come from annotations, requiredness from whether a default exists, and
    descriptions from keyword arguments named after the parameters. Keeping the
    schema derived from the function means the two cannot drift apart.
    """

    def decorate(fn: Callable[..., Any]) -> Tool:
        sig = inspect.signature(fn)
        params: list[Param] = []
        for pname, p in sig.parameters.items():
            if pname == "self":
                continue
            if p.annotation is inspect.Parameter.empty:
                raise TypeError(
                    f"tool {fn.__name__!r}: parameter {pname!r} needs a type annotation"
                )
            params.append(
                Param(
                    name=pname,
                    type=p.annotation,
                    description=param_docs.get(pname, ""),
                    required=p.default is inspect.Parameter.empty,
                )
            )
        desc = description or (inspect.getdoc(fn) or "").strip().split("\n")[0]
        if not desc:
            raise TypeError(f"tool {fn.__name__!r} needs a description")
        return Tool(
            name=name or fn.__name__,
            description=desc,
            params=tuple(params),
            fn=fn,
            mutating=mutating,
            requires_confirmation=requires_confirmation,
            timeout=timeout,
        )

    return decorate


# --------------------------------------------------------------------------
# Registry
# --------------------------------------------------------------------------


@dataclass
class ToolResult:
    call_id: str
    name: str
    ok: bool
    content: str
    duration_ms: float = 0.0

    def as_message(self):
        from .model import Message

        return Message(role="tool", content=self.content, tool_call_id=self.call_id)


ConfirmFn = Callable[[str, dict[str, Any]], bool]


class Registry:
    """The set of tools available for one run, plus the gates around them.

    `allowed` is the per-context allowlist. Exposing every tool you own to every
    context is how an injected instruction reaches something it should not: the
    fix is to scope the tool set to the task.
    """

    def __init__(
        self,
        tools: list[Tool] | None = None,
        allowed: set[str] | None = None,
        confirm: ConfirmFn | None = None,
    ) -> None:
        self._tools: dict[str, Tool] = {}
        for t in tools or []:
            self.add(t)
        self.allowed = allowed
        self.confirm = confirm

    def add(self, t: Tool) -> "Registry":
        if t.name in self._tools:
            raise ValueError(f"duplicate tool name {t.name!r}")
        self._tools[t.name] = t
        return self

    def __contains__(self, name: object) -> bool:
        return name in self._tools

    def __len__(self) -> int:
        return len(self.visible())

    def visible(self) -> list[Tool]:
        """Tools the model is told about - the allowlist applied."""
        return [
            t
            for name, t in self._tools.items()
            if self.allowed is None or name in self.allowed
        ]

    def schemas(self) -> list[dict[str, Any]]:
        return [t.to_schema() for t in self.visible()]

    def scoped(self, allowed: set[str]) -> "Registry":
        """A narrower view of the same tools, for a sub-task or a sub-agent."""
        r = Registry(confirm=self.confirm)
        r._tools = self._tools
        r.allowed = allowed if self.allowed is None else (allowed & self.allowed)
        return r

    # -- dispatch -------------------------------------------------------

    def dispatch(self, call) -> ToolResult:
        """Validate, authorize, then run one ToolCall. Never raises ToolError."""
        started = time.monotonic()

        def done(ok: bool, content: str) -> ToolResult:
            return ToolResult(
                call_id=call.id,
                name=call.name,
                ok=ok,
                content=content,
                duration_ms=(time.monotonic() - started) * 1000,
            )

        t = self._tools.get(call.name)
        if t is None or (self.allowed is not None and call.name not in self.allowed):
            # Same message either way: do not leak the existence of tools the
            # model is not allowed to see.
            names = sorted(x.name for x in self.visible())
            return done(False, f"Error: no such tool {call.name!r}. Available: {names}")

        try:
            args = t.validate(call.arguments)
        except ToolError as exc:
            return done(False, f"Error: {exc}")

        if t.requires_confirmation:
            if self.confirm is None:
                raise ToolConfigError(
                    f"tool {t.name!r} requires confirmation but this Registry has no "
                    f"confirm handler. Pass Registry(..., confirm=fn)."
                )
            if not self.confirm(t.name, args):
                return done(False, "Error: the user declined this action.")

        try:
            value = t.fn(**args)
        except ToolError as exc:
            # Expected, correctable: hand it back to the model.
            return done(False, f"Error: {exc}")
        except FatalToolError:
            raise
        except Exception as exc:  # noqa: BLE001 - deliberate boundary
            # Unexpected: do not leak internals to the model or the transcript.
            return done(False, f"Error: {t.name} failed internally ({type(exc).__name__}).")

        return done(True, _stringify(value))


def _stringify(value: Any) -> str:
    if isinstance(value, str):
        return value
    try:
        return json.dumps(value, default=str)
    except (TypeError, ValueError):
        return str(value)