# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-gen-ai-usage-token-counters-as-non-authoritative-across-a-retried-tool-call-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-gen-ai-usage-token-counters-as-non-authoritative-across-a-retried-tool-call-span.warrant.json
# Markdown SHA-256:   906c3620b1098d339e47ac02186a90077399fd8b2f66dc7a2d0cf20b06297cfb
# Code AST SHA-256:   4ce24c25874ae2063d5eeac8f243aac904428619c1edc6abea528b0aaa4fa875
# Verified Classes:   TokenAccountingInvariantError, GenAIChatSpan, FoldResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span set cannot be folded into an authoritative total."""


@dataclass(frozen=True)
class GenAIChatSpan:
    span_id: str
    parent_span_id: str | None
    operation_name: str            # gen_ai.operation.name
    model: str                     # gen_ai.request.model
    request_hash: str              # canonicalized request digest
    input_tokens: int              # gen_ai.usage.input_tokens
    output_tokens: int             # gen_ai.usage.output_tokens
    finish_reasons: tuple[str, ...]  # gen_ai.response.finish_reasons
    discarded: bool = False        # runtime-specific: output rejected by validation
    linked_from: str | None = None # SpanLink to prior attempt, if a retry


@dataclass
class FoldResult:
    billed_input: int = 0
    billed_output: int = 0
    consumed_input: int = 0
    consumed_output: int = 0
    deduped: int = 0
    discarded: int = 0
    seen_keys: set[tuple[str, str, str]] = field(default_factory=set)


def fold_authoritative_tokens(
    spans: Iterable[GenAIChatSpan],
    *,
    require_dedupe_key: bool = True,
) -> FoldResult:
    """
    Fold GenAI chat spans into authoritative billed/consumed totals.

    Billed = tokens the provider charged (deduped, discarded excluded).
    Consumed = tokens that occupied the context window (deduped, discarded included).

    Fails closed when the span set is ambiguous: unlinked sibling chat spans
    under one parent, or missing dedupe keys.
    """
    chat_spans = [s for s in spans if s.operation_name == "chat"]

    # Group by parent to detect unlinked siblings (retry vs parallel ambiguity).
    by_parent: dict[str | None, list[GenAIChatSpan]] = {}
    for s in chat_spans:
        by_parent.setdefault(s.parent_span_id, []).append(s)

    for parent, group in by_parent.items():
        if len(group) <= 1:
            continue
        linked_ids = {s.linked_from for s in group if s.linked_from}
        unlinked = [s for s in group if s.span_id not in linked_ids and s.linked_from is None]
        # If more than one span lacks a link to a prior attempt, we cannot tell
        # parallel calls from broken retry links.
        if len(unlinked) > 1 and not all(s.discarded for s in unlinked):
            raise TokenAccountingInvariantError(
                f"ambiguous sibling chat spans under parent={parent!r}: "
                f"{[s.span_id for s in unlinked]} have no SpanLink; "
                f"cannot distinguish parallel calls from unlinked retries"
            )

    result = FoldResult()
    for s in chat_spans:
        if require_dedupe_key:
            if not s.request_hash or not s.model or not s.operation_name:
                raise TokenAccountingInvariantError(
                    f"span {s.span_id!r} lacks a complete dedupe key "
                    f"(model={s.model!r}, request_hash={s.request_hash!r})"
                )
            key = (s.parent_span_id or "", s.model, s.request_hash)
            if key in result.seen_keys:
                result.deduped += 1
                continue
            result.seen_keys.add(key)

        result.consumed_input += s.input_tokens
        result.consumed_output += s.output_tokens

        if s.discarded:
            result.discarded += 1
            continue

        result.billed_input += s.input_tokens
        result.billed_output += s.output_tokens

    return result


def assert_within_budget(
    spans: Iterable[GenAIChatSpan],
    *,
    billed_budget_input: int,
    mode: str,
) -> FoldResult:
    """
    Enforce a token budget in authoritative mode. Raises if the span set is
    ambiguous (propagated from fold) or if the billed total exceeds budget.
    """
    if mode not in ("billed", "consumed"):
        raise TokenAccountingInvariantError(f"unknown accounting mode {mode!r}")

    result = fold_authoritative_tokens(spans, require_dedupe_key=True)

    used = (
        result.billed_input + result.billed_output
        if mode == "billed"
        else result.consumed_input + result.consumed_output
    )

    if used > billed_budget_input:
        raise TokenAccountingInvariantError(
            f"token budget exceeded in {mode} mode: used={used} "
            f"budget={billed_budget_input} "
            f"(deduped={result.deduped}, discarded={result.discarded})"
        )
    return result
