# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-genai-span-as-non-authoritative-for-cost-attribution-when-tool-call-attributes-diverge-from.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-opentelemetry-genai-span-as-non-authoritative-for-cost-attribution-when-tool-call-attributes-diverge-from.warrant.json
# Markdown SHA-256:   dff272650634e86a9304de6e812f234852f7970e09154154dba3f520d3ae63bd
# Code AST SHA-256:   6581f0a5c3cac8462b18ff49d5584ba28a3e5bb3a7b80fcf6b00063e5c96c5aa
# Verified Classes:   SpanAccountingError, GenAISpan
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class SpanAccountingError(RuntimeError):
    """Raised when a GenAI span tree cannot be trusted for cost attribution."""


@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    operation_name: str
    request_model: str | None
    input_tokens: int
    output_tokens: int
    aggregate: bool | None          # gen_ai.usage.aggregate
    attributed_to: str | None       # gen_ai.usage.attributed_to
    status_code: str                # OK | ERROR | UNSET
    timed_out: bool


MODEL_OPS = {"chat", "text_completion", "embeddings"}


def assert_cost_authoritative(spans: Iterable[GenAISpan]) -> None:
    """Validate the exactly-once cost invariant for one trace.

    Raises SpanAccountingError if the span tree is a valid debugging artifact
    but an invalid billing artifact. Callers must then fall back to the
    provider usage API for the trace window.
    """
    spans = list(spans)
    if not spans:
        raise SpanAccountingError("empty trace: no spans to attribute")

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise SpanAccountingError(
            f"mixed trace_ids in accounting set: {sorted(trace_ids)}"
        )

    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) > 1:
        ok_roots = [r for r in roots if r.status_code == "OK"]
        if len(ok_roots) > 1:
            raise SpanAccountingError(
                f"multiple OK roots under trace {roots[0].trace_id}: "
                f"retry shadow — usage would be double-counted"
            )

    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.operation_name not in MODEL_OPS:
            if s.input_tokens or s.output_tokens:
                raise SpanAccountingError(
                    f"usage on non-model span {s.span_id} "
                    f"({s.operation_name}): mis-tagged tokens"
                )
            continue

        if s.aggregate is None:
            raise SpanAccountingError(
                f"span {s.span_id} missing gen_ai.usage.aggregate: "
                f"ownership undeclared, cannot dedup"
            )

        parent = by_id.get(s.parent_span_id) if s.parent_span_id else None
        if parent is not None and parent.operation_name == "execute_tool":
            if s.attributed_to is None:
                raise SpanAccountingError(
                    f"nested model call {s.span_id} under tool span "
                    f"{parent.span_id} lacks gen_ai.usage.attributed_to: "
                    f"tokens would be attributed to the tool, not the agent"
                )

        ancestor_model = _nearest_model_ancestor_model(s, by_id)
        if ancestor_model is not None and ancestor_model != s.request_model:
            if s.aggregate is not False:
                raise SpanAccountingError(
                    f"mixed-model trace at {s.span_id}: "
                    f"{s.request_model} under {ancestor_model}, "
                    f"single-price-per-trace assumption broken"
                )

    for s in roots:
        if s.timed_out and s.status_code == "OK":
            raise SpanAccountingError(
                f"root {s.span_id} timed out but reports OK: "
                f"client abandon / server completion race"
            )


def _nearest_model_ancestor_model(span: GenAISpan, by_id: dict[str, GenAISpan]) -> str | None:
    cur = by_id.get(span.parent_span_id) if span.parent_span_id else None
    while cur is not None:
        if cur.operation_name in MODEL_OPS:
            return cur.request_model
        cur = by_id.get(cur.parent_span_id) if cur.parent_span_id else None
    return None
