# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-token-counts-against-the-provider-s-billed-usage-and-why-the-naive-sum-of-per-event-gen-ai-us.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-token-counts-against-the-provider-s-billed-usage-and-why-the-naive-sum-of-per-event-gen-ai-us.warrant.json
# Markdown SHA-256:   51a57589ada9901f55d17f4d117a4c07d01088b2be86d2459b224ed06c3a01f6
# Code AST SHA-256:   608753b8633724406afb9023b56774af8a8729789dd5b6ac25e398a4652c3a63
# Verified Classes:   TokenReconciliationError, TurnUsage, BilledUsage
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class TokenReconciliationError(RuntimeError):
    """Raised when span-derived token accounting cannot be reconciled to billed usage."""


@dataclass(frozen=True)
class TurnUsage:
    turn_index: int
    input_tokens: int                 # as emitted on gen_ai.usage.input_tokens
    output_tokens: int
    cached_input_tokens: Optional[int] = None  # gen_ai.usage.cached_input_tokens, if emitted


@dataclass(frozen=True)
class BilledUsage:
    input_tokens: int                 # authoritative, cache-exclusive uncached + cache reads at rate
    output_tokens: int


def reconcile(
    turns: list[TurnUsage],
    billed: BilledUsage,
    cache_read_rate: float = 0.10,
    tolerance: float = 0.15,
) -> dict:
    """
    Reconcile per-span GenAI usage against the provider's billed usage.

    Invariant enforced: billed_input is NOT the naive sum of per-turn input_tokens
    when prompt caching is active or when the agent re-sends context across turns.
    """
    if not turns:
        raise TokenReconciliationError("no turns to reconcile")

    multi_turn = len(turns) > 1
    has_cache_attr = all(t.cached_input_tokens is not None for t in turns)

    # Boundary: a multi-turn trace without cache attributes is not reconcilable
    # from span data alone -- the error is multiplicative, not additive.
    if multi_turn and not has_cache_attr:
        raise TokenReconciliationError(
            f"multi-turn trace ({len(turns)} turns) lacks gen_ai.usage.cached_input_tokens; "
            "span-derived cost would over-report cached-prefix re-sends. "
            "Use provider billing API as authoritative and mark estimate unreconciled."
        )

    span_input = 0.0
    for t in turns:
        if has_cache_attr:
            cached = t.cached_input_tokens or 0
            uncached = t.input_tokens - cached
            if uncached < 0:
                raise TokenReconciliationError(
                    f"turn {t.turn_index}: cached_input_tokens ({cached}) exceeds "
                    f"input_tokens ({t.input_tokens}); emitter definition mismatch"
                )
            span_input += uncached + cached * cache_read_rate
        else:
            # single-turn, no cache: span attribute is the billed amount
            span_input += t.input_tokens

    span_output = sum(t.output_tokens for t in turns)

    if span_output != billed.output_tokens:
        raise TokenReconciliationError(
            f"output mismatch: span={span_output} billed={billed.output_tokens}; "
            "output is never cached or re-sent, so this indicates a dropped span"
        )

    denom = max(billed.input_tokens, 1)
    input_drift = abs(span_input - billed.input_tokens) / denom
    if input_drift > tolerance:
        raise TokenReconciliationError(
            f"input drift {input_drift:.1%} exceeds tolerance {tolerance:.0%}: "
            f"span_reconciled={span_input:.0f} billed={billed.input_tokens}; "
            "check cache_read_rate, cache-attribute presence, and tool-loop accounting"
        )

    return {
        "span_reconciled_input": span_input,
        "billed_input": billed.input_tokens,
        "input_drift": input_drift,
        "output_tokens": span_output,
        "reconciled": True,
    }
