# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-an-agent-span-is-exported-after-the-model-span-it-summarizes-has-already-be.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-an-agent-span-is-exported-after-the-model-span-it-summarizes-has-already-be.warrant.json
# Markdown SHA-256:   fff8d5f1b98b97e507d38aa833c5cf4d8426b479774009a0a1719b39c0dd1bd6
# Code AST SHA-256:   33ec1bc472e2f64dfbed7b84454b9e491d8fc313f4178fdd93dde320d6849164
# Verified Classes:   TokenAccountingInvariantError, UsageRecord, AgentSpanState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAccountingInvariantError(RuntimeError):
    """Raised when an agent span's GenAI token attributes cannot be reconciled
    against the model-call usage records it claims to summarize."""


@dataclass
class UsageRecord:
    input_tokens: int
    output_tokens: int


@dataclass
class AgentSpanState:
    span_recording: bool
    observed_usage: list[UsageRecord] = field(default_factory=list)
    written_input_tokens: int | None = None
    written_output_tokens: int | None = None
    reconciled: bool = False


def record_model_call(state: AgentSpanState, usage: UsageRecord | None) -> None:
    # Accumulate from the provider response, NOT from child span attributes.
    # Sampling of the child span must never gate the parent's accounting.
    if usage is None:
        # Provider omitted usage: the sum is now unrepresentable.
        state.observed_usage.append(UsageRecord(0, 0))
        return
    state.observed_usage.append(usage)


def finalize_agent_span(state: AgentSpanState) -> AgentSpanState:
    if not state.span_recording:
        # RECORD_ONLY / dropped parent: do not write span attributes at all.
        # Caller must route usage to gen_ai.client.token.usage metrics instead.
        state.reconciled = False
        return state

    total_in = sum(u.input_tokens for u in state.observed_usage)
    total_out = sum(u.output_tokens for u in state.observed_usage)

    if state.written_input_tokens is not None and state.written_input_tokens != total_in:
        raise TokenAccountingInvariantError(
            f"agent span input_tokens={state.written_input_tokens} "
            f"!= observed sum={total_in}"
        )
    if state.written_output_tokens is not None and state.written_output_tokens != total_out:
        raise TokenAccountingInvariantError(
            f"agent span output_tokens={state.written_output_tokens} "
            f"!= observed sum={total_out}"
        )

    # A zero-token model call with no usage record means the sum is a lie.
    if any(u.input_tokens == 0 and u.output_tokens == 0 for u in state.observed_usage):
        state.written_input_tokens = None
        state.written_output_tokens = None
        state.reconciled = False
        raise TokenAccountingInvariantError(
            "usage record missing for one or more model calls; "
            "refusing to export partial gen_ai.usage.* on agent span"
        )

    state.written_input_tokens = total_in
    state.written_output_tokens = total_out
    state.reconciled = True
    return state
