# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-genai-token-accounting-drift-from-silently-corrupting-agent-turn-level-cost-attribution-across-retries-and-streaming-par.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-genai-token-accounting-drift-from-silently-corrupting-agent-turn-level-cost-attribution-across-retries-and-streaming-par.warrant.json
# Markdown SHA-256:   d04eb8a7f95a45766618c1ce44ca2a4d4c6488988cea461269458548b877d58d
# Code AST SHA-256:   67835c1f93affb4b84e4ce40c8b2372e5c99c1a147898cb1255ee96e03d851e2
# Verified Classes:   TurnAccountingInvariantError, Attempt, TurnLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TurnAccountingInvariantError(RuntimeError):
    """Raised when a turn's terminal usage record cannot be reconciled exactly once."""


@dataclass
class Attempt:
    attempt: int
    terminal: bool
    input_tokens: int = 0
    output_tokens: int = 0
    response_id: Optional[str] = None
    billed_on_receipt: bool = False  # provider billed even though attempt failed


@dataclass
class TurnLedger:
    turn_id: str
    attempts: list[Attempt] = field(default_factory=list)

    def record(self, attempt: Attempt) -> None:
        self.attempts.append(attempt)

    def reconcile(self) -> tuple[int, int]:
        terminal = [a for a in self.attempts if a.terminal]
        if len(terminal) != 1:
            raise TurnAccountingInvariantError(
                f"turn {self.turn_id}: expected exactly 1 terminal attempt, "
                f"found {len(terminal)}; cannot attribute cost exactly once"
            )
        win = terminal[0]
        # Failed attempts billed on receipt are real cost, but must be
        # attributed to the turn as 'wasted' not folded into the terminal sum.
        wasted_in = sum(
            a.input_tokens for a in self.attempts
            if not a.terminal and a.billed_on_receipt
        )
        if win.response_id is None:
            raise TurnAccountingInvariantError(
                f"turn {self.turn_id}: terminal attempt missing response_id; "
                f"streaming partials cannot be reconciled"
            )
        return win.input_tokens + wasted_in, win.output_tokens


def attribute_turn(ledger: TurnLedger) -> dict:
    try:
        inp, out = ledger.reconcile()
    except TurnAccountingInvariantError:
        raise
    return {"turn_id": ledger.turn_id, "input_tokens": inp, "output_tokens": out}
