# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-gen-ai-span-attributes-from-silently-misattributing-token-usage-across-retried-tool-call-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-gen-ai-span-attributes-from-silently-misattributing-token-usage-across-retried-tool-call-turns.warrant.json
# Markdown SHA-256:   4e5435eb1579d0fb2cce2f27ea99e9d01cfc6038fa0e1d458c46128543651aea
# Code AST SHA-256:   f8046d724cb9f45b94dd51368b9469b9669bce8c794a03f4ff7c65bcd3a34d79
# Verified Classes:   GenAiUsageInvariantError, GenAiSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAiUsageInvariantError(RuntimeError):
    """Raised when gen_ai.* span attributes violate the turn-accounting invariant."""


@dataclass
class GenAiSpan:
    turn_id: Optional[str]
    attempt_index: int
    model: str
    status: str  # "OK" | "ERROR"
    input_tokens: Optional[int]  # None == unknown, never coerce to 0
    output_tokens: Optional[int]
    tool_name: Optional[str] = None
    tool_call_id: Optional[str] = None
    attempt_billed: Optional[bool] = None


def aggregate_turn_cost(spans: list[GenAiSpan]) -> int:
    if not spans:
        return 0
    turn_ids = {s.turn_id for s in spans}
    if None in turn_ids or len(turn_ids) != 1:
        raise GenAiUsageInvariantError(
            f"turn_id must be set and identical across attempts; got {turn_ids}"
        )
    total = 0
    for s in spans:
        if s.status == "OK" and s.output_tokens is None:
            raise GenAiUsageInvariantError(
                f"OK span on turn {s.turn_id} attempt {s.attempt_index} "
                f"has unknown output_tokens; cannot aggregate cost"
            )
        if s.status == "ERROR" and s.attempt_billed is None:
            raise GenAiUsageInvariantError(
                f"failed attempt {s.attempt_index} on turn {s.turn_id} "
                f"lacks attempt.billed; billed-vs-aborted is undecidable"
            )
        if s.attempt_billed is False:
            continue
        # unknown usage on a billed attempt is a hard stop, not a zero
        if s.output_tokens is None:
            raise GenAiUsageInvariantError(
                f"billed attempt {s.attempt_index} on turn {s.turn_id} "
                f"missing gen_ai.usage.output_tokens"
            )
        total += s.output_tokens
    return total


def join_tool_result(spans: list[GenAiSpan], call_id: str) -> GenAiSpan:
    matches = [s for s in spans if s.tool_call_id == call_id]
    if not matches:
        raise GenAiUsageInvariantError(
            f"tool result call_id={call_id} has no originating attempt span; "
            f"retry likely minted a fresh id instead of reusing intent-time id"
        )
    ok = [s for s in matches if s.status == "OK"]
    if len(ok) != 1:
        raise GenAiUsageInvariantError(
            f"expected exactly one OK attempt for call_id={call_id}, got {len(ok)}"
        )
    return ok[0]
