# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-span-s-gen-ai-usage-input-tokens-as-non-reconcilable-with-the-sum-of-its-recorded-gen-ai-tool-child-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-span-s-gen-ai-usage-input-tokens-as-non-reconcilable-with-the-sum-of-its-recorded-gen-ai-tool-child-spans.warrant.json
# Markdown SHA-256:   029018b7123af7e404c52ec0652d793cef5514bb8239b63465dcbf3b22bc34d5
# Code AST SHA-256:   5ea3b4bde49ba490f25e7931dd6f4674f0a629fffa608b946761ef3e33fdfd04
# Verified Classes:   TokenReconciliationError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenReconciliationError(RuntimeError):
    """Raised when token accounting crosses the invocation/tool domain boundary."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation_name: str          # "chat" | "execute_tool" | ...
    input_tokens: int | None
    output_tokens: int | None
    response_id: str | None
    tool_call_id: str | None


def reconcile_cost(spans: list[Span]) -> int:
    """Sum input tokens over invocation roots only, deduped by response id.

    Invocation root = operation 'chat' with no 'chat' ancestor. Tool spans and
    tool-internal model calls are partitioned out of the cost domain.
    """
    by_id = {s.span_id: s for s in spans}

    def has_chat_ancestor(span: Span) -> bool:
        cur = by_id.get(span.parent_id) if span.parent_id else None
        while cur is not None:
            if cur.operation_name == "chat":
                return True
            cur = by_id.get(cur.parent_id) if cur.parent_id else None
        return False

    seen_response: set[str] = set()
    total = 0
    for s in spans:
        if s.operation_name != "chat":
            continue
        if has_chat_ancestor(s):
            # A tool that internally invoked a model: its own invocation root,
            # but must not be folded into the outer parent's accounting.
            continue
        if s.input_tokens is None:
            raise TokenReconciliationError(
                f"invocation span {s.span_id} missing gen_ai.usage.input_tokens; "
                "cannot reconcile"
            )
        if s.response_id is not None:
            if s.response_id in seen_response:
                continue  # retry duplicate
            seen_response.add(s.response_id)
        total += s.input_tokens
    return total


def attribute_tool_cost(spans: list[Span], parent_input_tokens: int) -> dict[str, int]:
    """REFUSES to attribute tokens to tool children: not defined by conventions."""
    tool_children = [s for s in spans if s.operation_name == "execute_tool"]
    if tool_children:
        raise TokenReconciliationError(
            f"{len(tool_children)} tool child span(s) present; per-tool token "
            "attribution is undefined. Attribute by gen_ai.tool.call.id and "
            "payload size instead. Parent input_tokens="
            f"{parent_input_tokens} is a prompt snapshot, not a per-child delta."
        )
    return {}
