# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-single-logical-agent-span-fans-out-into-parallel-tool-call-child-spans-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-single-logical-agent-span-fans-out-into-parallel-tool-call-child-spans-th.warrant.json
# Markdown SHA-256:   7ad40e7da13153ad7ed289f8303b749ac83dd7a47b6946b5794fea9ab6a313a7
# Code AST SHA-256:   15afd4551caf84ad70c2de282095a9e22bef905c1efa2baa8e54dd9550114f56
# Verified Classes:   TokenReconciliationError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TokenReconciliationError(RuntimeError):
    """Raised when GenAI token usage cannot be reconciled under the count-once invariant."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str  # e.g. "invoke_agent", "execute_tool", "chat"
    input_tokens: int = 0
    output_tokens: int = 0
    is_leaf_model_invocation: bool = False
    closed: bool = True
    children: list[str] = field(default_factory=list)


def reconcile_trace_tokens(spans: Iterable[Span], wait_window_expired: bool) -> dict[str, int]:
    """Sum token usage over leaf model-invocation spans, counted exactly once.

    Enforces: root total == sum over leaf model spans, independent of close order.
    """
    by_id = {s.span_id: s for s in spans}
    if not by_id:
        raise TokenReconciliationError("empty trace: no spans to reconcile")

    unclosed = [s.span_id for s in by_id.values() if not s.closed]
    if unclosed and not wait_window_expired:
        raise TokenReconciliationError(
            f"cannot reconcile: {len(unclosed)} spans still open and wait window not expired"
        )

    # A span is a leaf model invocation iff it owns usage and has no descendant
    # that also owns usage. Intermediate nodes that merely aggregate must be excluded.
    def owns_usage(s: Span) -> bool:
        return s.input_tokens > 0 or s.output_tokens > 0

    leaves = [
        s for s in by_id.values()
        if s.is_leaf_model_invocation and owns_usage(s)
    ]
    if not leaves:
        raise TokenReconciliationError("no leaf model-invocation spans found; usage would be lost")

    # Guard against double counting: a span marked leaf must not have a usage-owning child.
    for s in leaves:
        for child_id in s.children:
            child = by_id.get(child_id)
            if child is not None and owns_usage(child):
                raise TokenReconciliationError(
                    f"double-count risk: leaf span {s.span_id} has usage-owning child {child_id}"
                )

    total_in = sum(s.input_tokens for s in leaves)
    total_out = sum(s.output_tokens for s in leaves)

    if wait_window_expired and unclosed:
        return {
            "gen_ai.usage.input_tokens": total_in,
            "gen_ai.usage.output_tokens": total_out,
            "gen_ai.usage.reconciliation": 1,  # partial marker, not a silent total
        }
    return {
        "gen_ai.usage.input_tokens": total_in,
        "gen_ai.usage.output_tokens": total_out,
        "gen_ai.usage.reconciliation": 0,
    }
