# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-in-opentelemetry-genai-agent-spans-when-tool-call-attributes-and-usage-semantics-diverge-mid-t.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-in-opentelemetry-genai-agent-spans-when-tool-call-attributes-and-usage-semantics-diverge-mid-t.warrant.json
# Markdown SHA-256:   d2d0df74077a4891d90c23d63077b4cd15fde0bb545acd78c45117ed8a78eeb7
# Code AST SHA-256:   7177b1b2f46cd96f353e1540baacca6b2890d993e70150e44bc42bced8613fac
# Verified Classes:   TokenAccountingDriftError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingDriftError(RuntimeError):
    """Raised when a GenAI trace's span structure violates the leaf-summation invariant."""


@dataclass
class GenAISpan:
    name: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)
    start_time: float = 0.0

    @property
    def has_usage(self) -> bool:
        return "gen_ai.usage.input_tokens" in self.attributes or \
               "gen_ai.usage.output_tokens" in self.attributes

    @property
    def tool_call_ids(self) -> set:
        raw = self.attributes.get("gen_ai.tool.call.id", "")
        return {x for x in raw.split(",") if x} if raw else set()

    @property
    def is_leaf(self) -> bool:
        return not self.children


def validate_leaf_summation(root: GenAISpan) -> int:
    """
    Returns the trusted total input tokens, or raises TokenAccountingDriftError
    if the trace structure makes the sum unreliable.
    """
    leaves = []
    stack = [root]
    while stack:
        span = stack.pop()
        if span.has_usage and not span.is_leaf:
            raise TokenAccountingDriftError(
                f"span {span.name!r} carries usage but has children; "
                f"rollup usage must go to a metric, not a span attribute"
            )
        if span.is_leaf and span.name == "chat":
            leaves.append(span)
        stack.extend(span.children)

    seen_ids: dict = {}
    total = 0
    for leaf in leaves:
        for cid in leaf.tool_call_ids:
            key = (cid, leaf.start_time)
            if cid in seen_ids and seen_ids[cid] != leaf.start_time:
                raise TokenAccountingDriftError(
                    f"duplicate gen_ai.tool.call.id {cid!r} across sibling chat spans "
                    f"at {seen_ids[cid]} and {leaf.start_time}; likely a retry emitted "
                    f"as a new span — dedupe or emit as a span event before summing"
                )
            seen_ids[cid] = leaf.start_time
        total += int(leaf.attributes.get("gen_ai.usage.input_tokens", 0))

    if not leaves:
        raise TokenAccountingDriftError(
            "no leaf chat spans with usage found; trace cannot be reconciled"
        )
    return total


def reconcile_or_quarantine(root: GenAISpan, provider_total: Optional[int]) -> str:
    try:
        trace_total = validate_leaf_summation(root)
    except TokenAccountingDriftError as exc:
        if provider_total is None:
            raise TokenAccountingDriftError(
                f"trace structurally unreliable and no provider total to reconcile: {exc}"
            ) from exc
        return "quarantined"
    if provider_total is not None and abs(trace_total - provider_total) > 0.05 * provider_total:
        return "reconcile"
    return "trusted"
