# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-span-level-token-accounting-when-an-opentelemetry-genai-tool-call-span-is-retried-under-the-same-trace-and-parent-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-span-level-token-accounting-when-an-opentelemetry-genai-tool-call-span-is-retried-under-the-same-trace-and-parent-pro.warrant.json
# Markdown SHA-256:   82f4e296a83d4e475ccd17588eca367d84081c55f605634edf7e18cc3ceafa07
# Code AST SHA-256:   fb1f149e47e4e755599b003675ccade37c6c65aab9fab83392122dafdf9364db
# Verified Classes:   GenAiUsageAggregationError, GenAiSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class GenAiUsageAggregationError(RuntimeError):
    """Raised when retried tool-call spans cannot be deduplicated safely."""


@dataclass(frozen=True)
class GenAiSpan:
    trace_id: str
    parent_span_id: str
    span_id: str
    operation_name: str
    tool_call_id: str | None
    attempt: int | None
    input_tokens: int
    output_tokens: int
    status_ok: bool
    attributes: dict = field(default_factory=dict)


def reconcile_usage(spans: Iterable[GenAiSpan]) -> dict:
    """Sum GenAI token usage per trace, deduplicating retried tool calls.

    Enforces two invariants:
      1. Every execute_tool span carries a non-None `attempt`.
      2. Tool spans never inherit gen_ai.usage.* from the parent LLM span.
    """
    totals: dict[str, dict] = {}
    seen: dict[tuple[str, str], GenAiSpan] = {}

    for span in spans:
        trace = totals.setdefault(
            span.trace_id, {"input_tokens": 0, "output_tokens": 0}
        )

        if span.operation_name == "execute_tool":
            if span.attempt is None:
                raise GenAiUsageAggregationError(
                    f"tool span {span.span_id} in trace {span.trace_id} "
                    f"missing gen_ai.attempt; retries are unreconcilable"
                )
            if span.input_tokens or span.output_tokens:
                raise GenAiUsageAggregationError(
                    f"tool span {span.span_id} carries gen_ai.usage.* "
                    f"({span.input_tokens}/{span.output_tokens}); "
                    f"parent attribute copy-through detected"
                )
            if span.tool_call_id is None:
                raise GenAiUsageAggregationError(
                    f"tool span {span.span_id} missing gen_ai.tool.call.id"
                )

            key = (span.trace_id, span.tool_call_id)
            prior = seen.get(key)
            if prior is None or (span.status_ok and not prior.status_ok) or (
                span.status_ok == prior.status_ok and span.attempt > (prior.attempt or 0)
            ):
                seen[key] = span
            continue

        trace["input_tokens"] += span.input_tokens
        trace["output_tokens"] += span.output_tokens

    return totals
