# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-token-counts-when-an-opentelemetry-genai-span-is-emitted-before-the-tool-result-returns.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-token-counts-when-an-opentelemetry-genai-span-is-emitted-before-the-tool-result-returns.warrant.json
# Markdown SHA-256:   d86417f402ab639558712a6ec3d16f02743d151f4fd4e7bff070f3040912ec43
# Code AST SHA-256:   4fdaf61f472a4df0e6f4a9fd123a2c80cbd0ed96216ff8267a45e176cf86fb3c
# Verified Classes:   UsageReconciliationError, InferenceSpan, AgentSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when an agent span's usage cannot be reconciled with child inference spans."""
    pass


@dataclass
class InferenceSpan:
    trace_id: str
    start_time: float
    input_tokens: int
    output_tokens: int
    cached_tokens: int = 0
    linked_agent_span_id: Optional[str] = None


@dataclass
class AgentSpan:
    trace_id: str
    span_id: str
    start_time: float
    end_time: float
    input_tokens: int
    output_tokens: int
    cached_tokens: int = 0
    finalized: bool = True
    child_inference: list = field(default_factory=list)


def reconcile_agent_usage(agent: AgentSpan, all_spans: list, grace: float = 120.0) -> dict:
    """
    Reconcile an agent span's declared usage against all inference spans that
    belong to the same logical turn (same trace, within time window, or linked).
    Raises if a partial agent span is treated as authoritative.
    """
    in_window = [
        s for s in all_spans
        if s.trace_id == agent.trace_id
        and agent.start_time <= s.start_time <= agent.end_time + grace
    ]
    linked = [
        s for s in all_spans
        if s.linked_agent_span_id == agent.span_id
    ]
    candidates = {id(s): s for s in in_window + linked}.values()

    summed_in = sum(s.input_tokens for s in candidates)
    summed_out = sum(s.output_tokens for s in candidates)
    summed_cached = sum(s.cached_tokens for s in candidates)

    declared = (agent.input_tokens, agent.output_tokens, agent.cached_tokens)
    reconciled = (summed_in, summed_out, summed_cached)

    if declared != reconciled:
        if agent.finalized:
            raise UsageReconciliationError(
                f"Agent span {agent.span_id} declared finalized usage {declared} "
                f"but trace contains {reconciled} across {len(list(candidates))} "
                f"inference spans; agent usage is a lower bound, not authoritative."
            )
        return {
            "authoritative": False,
            "declared": declared,
            "reconciled": reconciled,
            "orphaned_calls": len(linked),
        }

    return {
        "authoritative": True,
        "declared": declared,
        "reconciled": reconciled,
        "orphaned_calls": 0,
    }
