"""Tracing: the bug report for a non-deterministic system.

You cannot reproduce an agent failure by re-running it, so the trace *is* the
evidence. This is a deliberately small tracer - a few hundred lines you can read
in full - because the point of the lesson is what to capture, not which vendor
to buy. Swapping in a real backend later means replacing `Tracer.export`.

What every span carries: what went in, what came out, how long, what it cost,
and enough identity (model, prompt version) to attribute a regression.
"""

from __future__ import annotations

import json
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Iterator


# Fields whose values are redacted in exported traces. Prompts and tool
# arguments carry user data; logging them wholesale creates a compliance
# surface. Lesson 9 covers retention properly.
SENSITIVE_KEYS = {"api_key", "authorization", "password", "token", "secret", "ssn"}

REDACTED = "[redacted]"


@dataclass
class Span:
    name: str
    kind: str  # "run" | "model" | "tool" | "retrieval" | "eval"
    span_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
    parent_id: str | None = None
    started_at: float = field(default_factory=time.monotonic)
    ended_at: float | None = None
    attributes: dict[str, Any] = field(default_factory=dict)
    error: str | None = None

    @property
    def duration_ms(self) -> float:
        end = self.ended_at if self.ended_at is not None else time.monotonic()
        return (end - self.started_at) * 1000

    def set(self, **attrs: Any) -> "Span":
        self.attributes.update(attrs)
        return self

    def to_dict(self, redact: bool = True) -> dict[str, Any]:
        attrs = _redact(self.attributes) if redact else self.attributes
        d = {
            "span_id": self.span_id,
            "parent_id": self.parent_id,
            "name": self.name,
            "kind": self.kind,
            "duration_ms": round(self.duration_ms, 2),
            "attributes": attrs,
        }
        if self.error:
            d["error"] = self.error
        return d


def _redact(value: Any) -> Any:
    if isinstance(value, dict):
        return {
            k: (REDACTED if k.lower() in SENSITIVE_KEYS else _redact(v))
            for k, v in value.items()
        }
    if isinstance(value, list):
        return [_redact(v) for v in value]
    return value


class Tracer:
    """Collects spans for one run. Nest with `span()`.

        with tracer.span("agent.run", "run") as run:
            with tracer.span("model.call", "model") as s:
                s.set(input_tokens=120)
    """

    def __init__(self) -> None:
        self.spans: list[Span] = []
        self._stack: list[Span] = []

    # -- recording ------------------------------------------------------

    class _Ctx:
        def __init__(self, tracer: "Tracer", span: Span) -> None:
            self._tracer = tracer
            self.span = span

        def __enter__(self) -> Span:
            return self.span

        def __exit__(self, exc_type, exc, tb) -> bool:
            self.span.ended_at = time.monotonic()
            if exc is not None:
                self.span.error = f"{exc_type.__name__}: {exc}"
            self._tracer._stack.pop()
            return False  # never swallow

    def span(self, name: str, kind: str = "step", **attrs: Any) -> "_Ctx":
        s = Span(
            name=name,
            kind=kind,
            parent_id=self._stack[-1].span_id if self._stack else None,
            attributes=dict(attrs),
        )
        self.spans.append(s)
        self._stack.append(s)
        return Tracer._Ctx(self, s)

    # -- reading --------------------------------------------------------

    def of_kind(self, kind: str) -> list[Span]:
        return [s for s in self.spans if s.kind == kind]

    @property
    def total_input_tokens(self) -> int:
        return sum(int(s.attributes.get("input_tokens", 0)) for s in self.spans)

    @property
    def total_output_tokens(self) -> int:
        return sum(int(s.attributes.get("output_tokens", 0)) for s in self.spans)

    @property
    def total_cost(self) -> float:
        return sum(float(s.attributes.get("cost", 0.0)) for s in self.spans)

    def errors(self) -> list[Span]:
        return [s for s in self.spans if s.error]

    def export(self, redact: bool = True) -> str:
        """JSON Lines - one span per line, the shape most backends ingest."""
        return "\n".join(
            json.dumps(s.to_dict(redact=redact)) for s in self.spans
        )

    # -- human output ---------------------------------------------------

    def tree(self) -> str:
        """Indented view. The first thing you look at when a run misbehaves."""
        by_parent: dict[str | None, list[Span]] = {}
        for s in self.spans:
            by_parent.setdefault(s.parent_id, []).append(s)

        lines: list[str] = []

        def walk(parent: str | None, depth: int) -> None:
            for s in by_parent.get(parent, []):
                pad = "  " * depth
                bits = [f"{pad}{s.kind}:{s.name}", f"{s.duration_ms:.0f}ms"]
                if "input_tokens" in s.attributes or "output_tokens" in s.attributes:
                    bits.append(
                        f"tok {s.attributes.get('input_tokens', 0)}"
                        f"/{s.attributes.get('output_tokens', 0)}"
                    )
                if s.error:
                    bits.append(f"ERROR {s.error}")
                lines.append("  ".join(bits))
                walk(s.span_id, depth + 1)

        walk(None, 0)
        return "\n".join(lines)


class NullTracer(Tracer):
    """A tracer that records nothing. Lets callers avoid `if tracer` branches."""

    def span(self, name: str, kind: str = "step", **attrs: Any) -> "Tracer._Ctx":
        s = Span(name=name, kind=kind, attributes=dict(attrs))
        self._stack.append(s)
        return Tracer._Ctx(self, s)