# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-gen-ai-usage-output-tokens-disagree-with-the-sum-of-child-llm-spans-under-an-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-gen-ai-usage-output-tokens-disagree-with-the-sum-of-child-llm-spans-under-an-agent-span.warrant.json
# Markdown SHA-256:   db65905fa86a3e6a23c71c86204c47b6376fd492609dc35ab27869811f34f538
# Code AST SHA-256:   07d69be2ed49a5325292a73941be1e526cd08cb86f74d2e6736f7d49b9d5168b
# Verified Classes:   GenAICostReconciliationError, GenAISpan, Reconciliation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class GenAICostReconciliationError(RuntimeError):
    """Raised when agent-span usage cannot be reconciled with leaf-span usage."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: str | None
    operation: str  # "invoke_agent" | "chat" | "execute_tool"
    output_tokens: int | None
    request_id: str | None = None
    attempt: int = 0
    sampled_out: bool = False


@dataclass
class Reconciliation:
    agent_attribute: int
    leaf_sum: int
    retry_duplicates: int
    nested_tool_tokens: int
    delta_pct: float
    complete: bool
    notes: list[str] = field(default_factory=list)


def reconcile_agent_cost(
    spans: Iterable[GenAISpan],
    *,
    max_delta_pct: float = 5.0,
    require_complete_trace: bool = True,
) -> Reconciliation:
    spans = list(spans)
    agents = [s for s in spans if s.operation == "invoke_agent"]
    if len(agents) != 1:
        raise GenAICostReconciliationError(
            f"expected exactly one agent span, found {len(agents)}; "
            "multi-agent hierarchies require per-level reconciliation"
        )
    agent = agents[0]
    if agent.output_tokens is None:
        raise GenAICostReconciliationError(
            f"agent span {agent.span_id} carries no gen_ai.usage.output_tokens"
        )

    if any(s.sampled_out for s in spans) and require_complete_trace:
        raise GenAICostReconciliationError(
            "trace contains sampled-out spans; agent attribute and leaf sum "
            "are not comparable without completeness metadata"
        )

    retry_dupes = 0
    leaf_sum = 0
    nested_tool = 0
    for s in spans:
        if s.operation != "chat" or s.output_tokens is None:
            continue
        if s.request_id is not None and s.attempt > 0:
            retry_dupes += s.output_tokens
            continue
        leaf_sum += s.output_tokens
        parent = next((p for p in spans if p.span_id == s.parent_id), None)
        if parent is not None and parent.operation == "execute_tool":
            nested_tool += s.output_tokens

    delta_pct = 100.0 * abs(agent.output_tokens - leaf_sum) / max(agent.output_tokens, 1)

    notes: list[str] = []
    if retry_dupes:
        notes.append(f"retry duplicates excluded from agent aggregate: {retry_dupes}")
    if nested_tool:
        notes.append(f"nested tool LLM tokens invisible to agent aggregate: {nested_tool}")

    if delta_pct > max_delta_pct:
        raise GenAICostReconciliationError(
            f"agent attribute {agent.output_tokens} vs leaf sum {leaf_sum} "
            f"differ by {delta_pct:.1f}% (threshold {max_delta_pct}%); "
            f"retry_dupes={retry_dupes} nested_tool={nested_tool}. "
            "Agent usage is advisory; reconstruct from leaves before billing."
        )

    return Reconciliation(
        agent_attribute=agent.output_tokens,
        leaf_sum=leaf_sum,
        retry_duplicates=retry_dupes,
        nested_tool_tokens=nested_tool,
        delta_pct=delta_pct,
        complete=True,
        notes=notes,
    )
