# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-the-token-ledger-before-emitting-a-completion-and-why-the-nai.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-the-token-ledger-before-emitting-a-completion-and-why-the-nai.warrant.json
# Markdown SHA-256:   0161c0903de8c597eedfd57cefd1911955144be036cd3f91eb792a7f3a4c08a5
# Code AST SHA-256:   1f1d5fabdb8b9e915a9def34f6796d932b3f48f58e2de9c382343df7fd68da45
# Verified Classes:   UsageSource, TokenReconciliationError, AttemptUsage, GenAiSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class UsageSource(str, Enum):
    PROVIDER = "provider"
    LOCAL_TOKENIZER = "local_tokenizer"


class TokenReconciliationError(RuntimeError):
    """Raised when a span's attributed token counts cannot be reconciled
    against the authoritative provider usage record for the attempt."""


@dataclass
class AttemptUsage:
    """One transport attempt's usage, as reported by the provider."""
    attempt_id: str
    input_tokens: int
    output_tokens: int
    billed: bool  # aborted attempts are still billed
    authoritative: bool  # False if provider omitted the usage chunk


@dataclass
class GenAiSpan:
    span_id: str
    operation: str  # "chat" | "execute_tool"
    attributed_input: Optional[int] = None
    attributed_output: Optional[int] = None
    source: Optional[UsageSource] = None
    events: list = field(default_factory=list)


def close_chat_span(
    span: GenAiSpan,
    attempts: list[AttemptUsage],
    delivered_output_tokens: int,
) -> GenAiSpan:
    """Close a chat span, attributing tokens from the authoritative usage
    record across ALL billed attempts, not just the successful one.

    Invariant: sum(attributed) == sum(billed) across attempts in this span.
    """
    if span.operation != "chat":
        raise TokenReconciliationError(
            f"usage attribution only valid on chat spans, got {span.operation!r}"
        )
    if not attempts:
        raise TokenReconciliationError(
            f"span {span.span_id} closed with zero attempts; cannot attribute"
        )

    billed_attempts = [a for a in attempts if a.billed]
    if not billed_attempts:
        raise TokenReconciliationError(
            f"span {span.span_id}: no billed attempts, refusing to emit usage"
        )

    if not all(a.authoritative for a in billed_attempts):
        # Degrade to estimated mode; never assert provider authority.
        span.attributed_input = sum(a.input_tokens for a in billed_attempts)
        span.attributed_output = delivered_output_tokens
        span.source = UsageSource.LOCAL_TOKENIZER
        span.events.append(
            ("gen_ai.usage.reconciliation_failed", "provider usage chunk missing")
        )
        return span

    billed_in = sum(a.input_tokens for a in billed_attempts)
    billed_out = sum(a.output_tokens for a in billed_attempts)

    # The delivered count MUST NOT be used as the attributed count when an
    # authoritative record exists; retries and stop-sequences make it wrong.
    if billed_out != delivered_output_tokens:
        span.events.append(
            (
                "gen_ai.usage.mismatch",
                f"billed={billed_out} delivered={delivered_output_tokens} "
                f"delta={billed_out - delivered_output_tokens}",
            )
        )

    span.attributed_input = billed_in
    span.attributed_output = billed_out
    span.source = UsageSource.PROVIDER
    return span


def reconcile_trace(spans: list[GenAiSpan], invoice_tokens: int) -> None:
    """Assert trace-level sum equals provider invoice for provider-sourced spans."""
    provider_spans = [s for s in spans if s.source == UsageSource.PROVIDER]
    if not provider_spans:
        raise TokenReconciliationError(
            "trace has no provider-sourced spans; invoice cannot be reconciled"
        )
    trace_total = sum(
        (s.attributed_input or 0) + (s.attributed_output or 0) for s in provider_spans
    )
    if trace_total != invoice_tokens:
        raise TokenReconciliationError(
            f"trace token sum {trace_total} != invoice {invoice_tokens} "
            f"(delta {invoice_tokens - trace_total}); span ledger is corrupt"
        )
