# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-with-tool-call-attributes-but-no-parent-agent-span-breaking-trace-based-cost-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-with-tool-call-attributes-but-no-parent-agent-span-breaking-trace-based-cost-attribution.warrant.json
# Markdown SHA-256:   862e3f115fd6eec917b841804528efe56e335374392604197cf251f9e03f1c79
# Code AST SHA-256:   2c2f2f0108a73eca94b4fea116605a42fd3b015b3d6be55a6717b7d0929a9de9
# Verified Classes:   OrphanedUsageSpanError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class OrphanedUsageSpanError(RuntimeError):
    """A span carrying gen_ai token usage has no attributable agent run."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    operation_name: str
    attributes: dict = field(default_factory=dict)

    def has_usage(self) -> bool:
        return any(
            k in self.attributes
            for k in ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
        )

    def agent_run_id(self) -> Optional[str]:
        return self.attributes.get("gen_ai.agent.run_id")


def assert_usage_attributable(spans: list[Span]) -> dict[str, int]:
    """Return tokens grouped by run_id; raise if any usage span is orphaned."""
    by_id = {s.span_id: s for s in spans}
    totals: dict[str, int] = {}

    for span in spans:
        if not span.has_usage():
            continue

        run_id = span.agent_run_id()
        if run_id is None:
            # Fall back to walking the trace graph to an invoke_agent ancestor.
            cursor = span
            seen = set()
            while cursor.parent_span_id is not None:
                if cursor.span_id in seen:
                    break
                seen.add(cursor.span_id)
                parent = by_id.get(cursor.parent_span_id)
                if parent is None:
                    break
                if parent.operation_name == "invoke_agent":
                    run_id = parent.agent_run_id()
                    break
                cursor = parent

        if run_id is None:
            raise OrphanedUsageSpanError(
                f"span {span.span_id} (trace {span.trace_id}, "
                f"op={span.operation_name}) carries gen_ai usage "
                f"but has no attributable agent run: no gen_ai.agent.run_id "
                f"attribute and no invoke_agent ancestor in trace"
            )

        tokens = (
            span.attributes.get("gen_ai.usage.input_tokens", 0)
            + span.attributes.get("gen_ai.usage.output_tokens", 0)
        )
        totals[run_id] = totals.get(run_id, 0) + tokens

    return totals


def reconcile_run(run_id: str, spans: list[Span], reported_total: int) -> None:
    totals = assert_usage_attributable(spans)
    observed = totals.get(run_id, 0)
    if observed != reported_total:
        raise OrphanedUsageSpanError(
            f"run {run_id}: attributed tokens {observed} != reported {reported_total}; "
            f"attribution gap of {reported_total - observed} tokens"
        )
