# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-token-counters-when-a-retry-storm-double-counts-cached-prompt-tokens-across-a-span-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-token-counters-when-a-retry-storm-double-counts-cached-prompt-tokens-across-a-span-boundary.warrant.json
# Markdown SHA-256:   2931747e892af7e65c50dbeb963f0338f5762d35cc70739992bad08388c1e80a
# Code AST SHA-256:   ca22bc4143719d827566819f9a4539e1d7e2f2c62ff19371dc5d6c78e6fb9b51
# Verified Classes:   TokenReconciliationError, Attempt, OperationLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TokenReconciliationError(RuntimeError):
    """Raised when an operation's attempt set cannot be safely reconciled."""


@dataclass
class Attempt:
    operation_id: str
    attempt_index: int
    input_tokens: int
    output_tokens: int
    cache_read_input_tokens: int = 0
    terminal: bool = False
    error_status: str | None = None


@dataclass
class OperationLedger:
    operation_id: str
    context_window: int
    attempts: list[Attempt] = field(default_factory=list)

    def add(self, a: Attempt) -> None:
        if a.operation_id != self.operation_id:
            raise TokenReconciliationError(
                f"attempt {a.attempt_index} belongs to {a.operation_id}, "
                f"not {self.operation_id}"
            )
        self.attempts.append(a)

    def reconcile(self) -> dict:
        if not self.attempts:
            raise TokenReconciliationError(
                f"operation {self.operation_id} has no attempts to reconcile"
            )
        if not any(a.terminal for a in self.attempts):
            raise TokenReconciliationError(
                f"operation {self.operation_id} still open: "
                f"{len(self.attempts)} attempts, none terminal; "
                "refusing to publish aggregate (would double-count on later retry)"
            )

        # Attempt accounting: what the provider billed / rate-limited against.
        attempt_input = sum(a.input_tokens for a in self.attempts)
        attempt_output = sum(a.output_tokens for a in self.attempts)

        # Operation accounting: unique prompt content actually reasoned over.
        # Cache-read tokens were served from cache on that attempt, so the
        # unique input is the max single-attempt input minus its cache reads,
        # floored at the largest non-cached payload seen.
        unique_input = max(
            a.input_tokens - a.cache_read_input_tokens for a in self.attempts
        )
        cache_read = sum(a.cache_read_input_tokens for a in self.attempts)

        # The boundary check: context-viable but attempt-expensive.
        context_viable = unique_input <= self.context_window
        attempt_expensive = attempt_input > self.context_window
        if context_viable and attempt_expensive:
            # This is the regime where a naive budget guard misfires.
            # Emit both, tagged, and forbid the guard from reading attempt_input.
            pass

        if not context_viable:
            raise TokenReconciliationError(
                f"operation {self.operation_id}: unique input {unique_input} "
                f"exceeds context window {self.context_window}; "
                "compaction required before retry"
            )

        return {
            "operation_id": self.operation_id,
            "gen_ai.token.accounting=attempt": {
                "input": attempt_input,
                "output": attempt_output,
            },
            "gen_ai.token.accounting=operation": {
                "input": unique_input,
                "output": max(a.output_tokens for a in self.attempts),
                "cache_read": cache_read,
            },
            "attempt_count": len(self.attempts),
            "context_viable": context_viable,
        }


def close_operation(ledger: OperationLedger) -> dict:
    try:
        return ledger.reconcile()
    except TokenReconciliationError:
        # Orphaned attempt set: do not silently sum. Emit a sentinel so
        # downstream cost meters and budget guards fail closed.
        raise
