# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-token-accounting-as-non-additive-across-a-tool-call-chain-and-how-does-span-parenting-cor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-token-accounting-as-non-additive-across-a-tool-call-chain-and-how-does-span-parenting-cor.warrant.json
# Markdown SHA-256:   3e15cf69d55d0ab10415cb8e8c2d1c90b602d71afc63f0b3a295237ec37bcd27
# Code AST SHA-256:   ee0efe8b205a77f27668bb37a59f0a7cb3117e25c4da486b886f51c9f3b2b5a7
# Verified Classes:   TokenRollupInvariantError, Span, ChainRollup
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class TokenRollupInvariantError(RuntimeError):
    """Raised when a GenAI span tree cannot be safely aggregated for token accounting."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str          # "chat" | "execute_tool" | "invoke_agent"
    input_tokens: int = 0
    output_tokens: int = 0
    response_id: str | None = None
    response_model: str | None = None


@dataclass
class ChainRollup:
    billed_input_total: int
    billed_output_total: int
    context_depth: int
    regime: str
    chat_span_ids: list[str] = field(default_factory=list)


def _is_ancestor(anc: Span, node: Span, by_id: dict[str, Span]) -> bool:
    cur = node
    while cur.parent_id is not None:
        if cur.parent_id == anc.span_id:
            return True
        cur = by_id[cur.parent_id]
    return False


def rollup_chain(spans: list[Span]) -> ChainRollup:
    by_id = {s.span_id: s for s in spans}

    # Clause 1: usage must be terminal, not inherited. A span with usage but
    # no response_id is a propagated copy and must be excluded, not summed.
    chat_spans = [
        s for s in spans
        if s.operation == "chat" and (s.input_tokens or s.output_tokens)
    ]
    inherited = [s for s in chat_spans if s.response_id is None]
    if inherited:
        raise TokenRollupInvariantError(
            f"chat spans with usage but no response_id (inherited attributes): "
            f"{[s.span_id for s in inherited]}"
        )

    # Clause 2: the summed set must be an antichain.
    for i, a in enumerate(chat_spans):
        for b in chat_spans[i + 1:]:
            if _is_ancestor(a, b, by_id) or _is_ancestor(b, a, by_id):
                raise TokenRollupInvariantError(
                    f"ancestral chat spans in rollup: {a.span_id} vs {b.span_id}"
                )

    # Clause 3: response IDs must be unique within the set.
    seen: dict[str, str] = {}
    for s in chat_spans:
        assert s.response_id is not None
        if s.response_id in seen:
            raise TokenRollupInvariantError(
                f"duplicate gen_ai.response.id {s.response_id!r} on "
                f"{seen[s.response_id]} and {s.span_id}"
            )
        seen[s.response_id] = s.span_id

    if not chat_spans:
        raise TokenRollupInvariantError("no billable chat spans in tree")

    billed_in = sum(s.input_tokens for s in chat_spans)
    billed_out = sum(s.output_tokens for s in chat_spans)
    context_depth = max(s.input_tokens for s in chat_spans)
    ratio = billed_in / context_depth if context_depth else 0.0
    regime = "re-billing" if ratio > 1.5 else "single-shot"

    return ChainRollup(
        billed_input_total=billed_in,
        billed_output_total=billed_out,
        context_depth=context_depth,
        regime=regime,
        chat_span_ids=[s.span_id for s in chat_spans],
    )
