# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-call-spans-when-opentelemetry-genai-token-accounting-diverges-from-the-agent-s-own-budget-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-call-spans-when-opentelemetry-genai-token-accounting-diverges-from-the-agent-s-own-budget-ledger.warrant.json
# Markdown SHA-256:   124be7d267f64932e40616b347a20209719287226e3a5b1a044bfed13a0db35d
# Code AST SHA-256:   92edb80326c009e11ab21c7d536d469646e4e24d66c500def09d471d6c6ec78a
# Verified Classes:   OrphanedToolSpanError, UnattributableTokenDivergence, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class OrphanedToolSpanError(RuntimeError):
    """Raised when a gen_ai.chat span references a tool-call id with no matching gen_ai.tool span."""
    pass


class UnattributableTokenDivergence(RuntimeError):
    """Raised when ledger/OTel token divergence cannot be explained by a single orphaned span."""
    pass


@dataclass
class Span:
    name: str
    attrs: dict = field(default_factory=dict)
    children: list = field(default_factory=list)

    def input_tokens(self) -> int:
        return int(self.attrs.get("gen_ai.usage.input_tokens", 0))


def find_orphaned_tool_calls(root: Span) -> list[str]:
    """Return tool-call ids referenced by chat spans but absent from tool spans."""
    referenced, present = set(), set()

    def walk(s: Span):
        if s.name == "gen_ai.chat":
            cid = s.attrs.get("gen_ai.tool_call.id")
            if cid:
                referenced.add(cid)
        if s.name == "gen_ai.tool":
            cid = s.attrs.get("gen_ai.tool.call.id")
            if cid:
                present.add(cid)
        for c in s.children:
            walk(c)

    walk(root)
    return sorted(referenced - present)


def reconcile(ledger_total: int, root: Span) -> int:
    """
    Reconcile ledger against OTel root. Auto-heals ONLY a single-attributable orphan.
    Returns the corrected ledger total.
    """
    otel_total = root.input_tokens()
    divergence = ledger_total - otel_total
    orphans = find_orphaned_tool_calls(root)

    if divergence == 0 and not orphans:
        return ledger_total

    if len(orphans) == 1:
        orphan_tokens = _orphan_input_tokens(root, orphans[0])
        if divergence == orphan_tokens:
            # ledger double-counted the re-send; subtract it and close the hierarchy
            _close_orphan(root, orphans[0])
            return ledger_total - orphan_tokens
        raise UnattributableTokenDivergence(
            f"divergence {divergence} != orphan tokens {orphan_tokens} for {orphans[0]}"
        )

    if orphans:
        raise OrphanedToolSpanError(
            f"{len(orphans)} orphaned tool-call ids: {orphans}; refusing auto-heal"
        )
    raise UnattributableTokenDivergence(
        f"divergence {divergence} with no orphaned span to attribute it to"
    )


def _orphan_input_tokens(root: Span, call_id: str) -> int:
    def walk(s: Span):
        if s.name == "gen_ai.chat" and s.attrs.get("gen_ai.tool_call.id") == call_id:
            return s.input_tokens()
        for c in s.children:
            r = walk(c)
            if r is not None:
                return r
        return None

    r = walk(root)
    if r is None:
        raise OrphanedToolSpanError(f"call id {call_id} referenced but chat span not found")
    return r


def _close_orphan(root: Span, call_id: str) -> None:
    """Emit a synthetic error tool span to restore the referential invariant."""
    root.children.append(
        Span(
            name="gen_ai.tool",
            attrs={
                "gen_ai.tool.call.id": call_id,
                "error.type": "interrupted",
                "gen_ai.tool.name": "unknown",
            },
        )
    )
