# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-per-turn-token-accounting-as-non-additive-across-trace-spans-in-genai-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-per-turn-token-accounting-as-non-additive-across-trace-spans-in-genai-observability-pipelines.warrant.json
# Markdown SHA-256:   b951961e99931079d550de513e8b89730d0861d0b292a230303278972a548b30
# Code AST SHA-256:   479e6d31c416e749ec385f0335155db9872bc2fd9a3c24abf4b16a07bdfb12c0
# Verified Classes:   AmbiguousUsageAuthorityError, Authority, UsageSpan, TurnCost
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class AmbiguousUsageAuthorityError(RuntimeError):
    """Raised when a turn's token cost cannot be attributed to a single authority span."""


class Authority(Enum):
    EXPLICIT = "explicit"
    INFERRED = "inferred"


@dataclass(frozen=True)
class UsageSpan:
    span_id: str
    parent_id: str | None
    input_tokens: int
    output_tokens: int
    declares_exclusive: bool = False
    drains_stream: bool = False

    @property
    def total(self) -> int:
        return self.input_tokens + self.output_tokens


@dataclass(frozen=True)
class TurnCost:
    turn_id: str
    authority_span_id: str
    authority: Authority
    billable_tokens: int
    shadow_tokens: int
    divergence: float
    warnings: tuple[str, ...] = field(default_factory=tuple)


TOLERANCE = 0.02  # 2% divergence between summed observations and elected authority


def resolve_turn_cost(
    turn_id: str, spans: Iterable[UsageSpan], *, tolerance: float = TOLERANCE
) -> TurnCost:
    spans = list(spans)
    if not spans:
        raise AmbiguousUsageAuthorityError(
            f"turn {turn_id!r}: no usage-bearing spans; cannot elect authority"
        )

    explicit = [s for s in spans if s.declares_exclusive]
    warnings: list[str] = []

    if len(explicit) > 1:
        raise AmbiguousUsageAuthorityError(
            f"turn {turn_id!r}: multiple spans declare usage_authority=exclusive: "
            f"{[s.span_id for s in explicit]}"
        )

    if explicit:
        authority_span, authority = explicit[0], Authority.EXPLICIT
    else:
        stream_drainers = [s for s in spans if s.drains_stream]
        if len(stream_drainers) == 1:
            authority_span, authority = stream_drainers[0], Authority.INFERRED
            warnings.append("usage_authority_inferred:selected_stream_drainer")
        elif len(stream_drainers) > 1:
            raise AmbiguousUsageAuthorityError(
                f"turn {turn_id!r}: multiple stream-draining spans, no declared authority: "
                f"{[s.span_id for s in stream_drainers]}"
            )
        else:
            authority_span, authority = spans[-1], Authority.INFERRED
            warnings.append("usage_authority_inferred:selected_last_span")

    summed = sum(s.total for s in spans)
    billable = authority_span.total
    shadow = summed - billable
    divergence = (shadow / billable) if billable else float("inf")

    if divergence > tolerance:
        raise AmbiguousUsageAuthorityError(
            f"turn {turn_id!r}: authority span {authority_span.span_id!r} reports "
            f"{billable} tokens but summed observations are {summed} "
            f"(divergence {divergence:.1%} > tolerance {tolerance:.1%}); "
            f"refusing to emit cost figure"
        )

    return TurnCost(
        turn_id=turn_id,
        authority_span_id=authority_span.span_id,
        authority=authority,
        billable_tokens=billable,
        shadow_tokens=shadow,
        divergence=divergence,
        warnings=tuple(warnings),
    )
