# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-across-parent-child-agent-spans-when-tool-call-attributes-are-emitted-after-the-model-invocation-event.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-across-parent-child-agent-spans-when-tool-call-attributes-are-emitted-after-the-model-invocation-event.warrant.json
# Markdown SHA-256:   d5d9e50d42ba02dab9b2a273c086f5cfb31636e092a250b855628ba265a0d304
# Code AST SHA-256:   cd9d29fda93f15f989d441d3465c8512ac4f9fb8d00b70f45446757f9f49c75d
# Verified Classes:   UsageInvariantError, GenAISpan
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageInvariantError(RuntimeError):
    """Raised when parent/child GenAI token accounting cannot be proven consistent."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    kind: str  # "invoke_agent" | "chat" | "execute_tool"
    input_tokens: int = 0
    output_tokens: int = 0
    tool_call_id: Optional[str] = None
    usage_partial: bool = False
    exported: bool = False
    ended: bool = False


def finalize_and_export(span: GenAISpan, export_fn) -> None:
    if not span.ended:
        raise UsageInvariantError(
            f"span {span.span_id} exported before end(); usage is not terminal"
        )
    if span.kind == "chat" and span.usage_partial:
        raise UsageInvariantError(
            f"chat span {span.span_id} has partial usage; cannot export as terminal"
        )
    span.exported = True
    export_fn(span)


def aggregate_parent_usage(parent: GenAISpan, children: list[GenAISpan]) -> int:
    if parent.kind != "invoke_agent":
        raise UsageInvariantError(f"span {parent.span_id} is not an agent span")
    if parent.input_tokens != 0:
        raise UsageInvariantError(
            f"parent {parent.span_id} carries aggregated usage; double-count risk"
        )

    seen_span_ids: set[str] = set()
    total = 0
    for child in children:
        if child.parent_span_id != parent.span_id:
            raise UsageInvariantError(
                f"child {child.span_id} does not belong to parent {parent.span_id}"
            )
        if child.kind != "chat":
            continue
        if not child.ended or child.usage_partial:
            raise UsageInvariantError(
                f"child {child.span_id} causal closure not proven before parent close"
            )
        if child.span_id in seen_span_ids:
            raise UsageInvariantError(
                f"duplicate span_id {child.span_id} in aggregation"
            )
        seen_span_ids.add(child.span_id)
        total += child.input_tokens + child.output_tokens
    return total


def dedup_retries_by_tool_call(children: list[GenAISpan]) -> list[GenAISpan]:
    # NOTE: safe ONLY for tool side-effect idempotency, NEVER for usage.
    seen: dict[str, GenAISpan] = {}
    for c in children:
        if c.kind != "chat" or c.tool_call_id is None:
            continue
        if c.tool_call_id in seen and seen[c.tool_call_id].span_id != c.span_id:
            raise UsageInvariantError(
                f"retry of tool_call {c.tool_call_id} has distinct span_id "
                f"{c.span_id}; must count as a separate invocation, not dedup"
            )
        seen[c.tool_call_id] = c
    return list(seen.values())
