# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-spans-whose-genai-usage-input-tokens-disagrees-with-the-provider-s-billed-prompt-token-c.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-spans-whose-genai-usage-input-tokens-disagrees-with-the-provider-s-billed-prompt-token-c.warrant.json
# Markdown SHA-256:   1161247b2ded9e137229b1fe13a9db766336453a4b77ae8c25710a8e4ff5b845
# Code AST SHA-256:   44a4a6312e64678c5ab13c92ca0ca42d2b7a7a26a4d456376b5f04937b87f789
# Verified Classes:   AccountingRegime, TokenAccountingError, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AccountingRegime(Enum):
    BILLED_PROMPT = "billed_prompt"      # includes cached prefix, sums across calls
    CONTEXT_OCCUPANCY = "occupancy"      # peak context, max across calls


class TokenAccountingError(RuntimeError):
    """Raised when a GenAI span trace cannot be reduced to a reconcilable total."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    input_tokens: int
    output_tokens: int
    finish_reasons: tuple[str, ...]
    regime_marker: str | None


def reduce_trace_tokens(
    spans: list[GenAISpan],
    regime: AccountingRegime,
    provider_aggregate: int,
    tolerance: int = 0,
) -> int:
    if not spans:
        raise TokenAccountingError("empty trace: nothing to reduce")

    markers = {s.regime_marker for s in spans}
    if len(markers) > 1:
        raise TokenAccountingError(
            f"regime discontinuity across trace: markers={markers}"
        )

    for prev, cur in zip(spans, spans[1:]):
        if cur.input_tokens < prev.input_tokens and not cur.finish_reasons:
            raise TokenAccountingError(
                f"non-monotonic prompt growth at {cur.span_id} "
                f"({prev.input_tokens} -> {cur.input_tokens}) with no truncation marker"
            )

    for s in spans:
        if s.output_tokens > 0 and not s.finish_reasons:
            raise TokenAccountingError(
                f"span {s.span_id} has output tokens but no finish reason; "
                "prompt may be billed without a recorded completion"
            )

    if regime is AccountingRegime.BILLED_PROMPT:
        total = sum(s.input_tokens for s in spans)
    elif regime is AccountingRegime.CONTEXT_OCCUPANCY:
        total = max(s.input_tokens for s in spans)
    else:
        raise TokenAccountingError(f"unknown regime {regime!r}")

    delta = provider_aggregate - total
    if abs(delta) > tolerance:
        raise TokenAccountingError(
            f"reconciliation delta {delta} exceeds tolerance {tolerance} "
            f"under regime {regime.value}; quarantine trace for audit"
        )

    return total
