# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-otel-genai-span-closure-against-late-token-usage-callbacks-when-tool-call-spans-outlive-the-parent-llm-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-otel-genai-span-closure-against-late-token-usage-callbacks-when-tool-call-spans-outlive-the-parent-llm-span.warrant.json
# Markdown SHA-256:   023832a321e86cbff89d9ed838ca57513d99f812919da514380f04e6eda949be
# Code AST SHA-256:   ae671b42b2b10bd0a66ca68cbdd950ded4c36a5c080900500145044ce475f3b6
# Verified Classes:   UsageReconciliationError, ClosedChatSpan, UsageCallback, ReconciliationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a chat span's usage cannot be reconciled exactly once."""


@dataclass
class ClosedChatSpan:
    span_id: str
    trace_id: str
    model: str
    ended_at: float
    usage_attributes_set: bool = False  # True only if set before end()


@dataclass
class UsageCallback:
    span_id: str
    response_id: str
    input_tokens: int
    output_tokens: int
    arrived_at: float


@dataclass
class ReconciliationLedger:
    spans: dict[str, ClosedChatSpan] = field(default_factory=dict)
    reconciled: dict[str, str] = field(default_factory=dict)  # span_id -> carrier
    usage_timeout_s: float = 2.0

    def register_closed_span(self, span: ClosedChatSpan) -> None:
        if span.span_id in self.spans:
            raise UsageReconciliationError(
                f"duplicate span_id {span.span_id} registered; span identity must be unique"
            )
        self.spans[span.span_id] = span

    def on_usage(self, cb: UsageCallback) -> str:
        span = self.spans.get(cb.span_id)
        if span is None:
            raise UsageReconciliationError(
                f"usage callback for unknown span {cb.span_id}; "
                f"cannot attribute tokens to a span that was never registered"
            )
        if cb.span_id in self.reconciled:
            # idempotent replay: do not double-emit
            return self.reconciled[cb.span_id]
        if span.usage_attributes_set:
            # synchronous provider path: span already authoritative
            self.reconciled[cb.span_id] = "span_attribute"
            return "span_attribute"
        # streaming path: span is closed and immutable; route to metric carrier
        if cb.arrived_at - span.ended_at > self.usage_timeout_s:
            raise UsageReconciliationError(
                f"usage for span {cb.span_id} arrived "
                f"{cb.arrived_at - span.ended_at:.2f}s after end, "
                f"exceeds T_usage={self.usage_timeout_s}s; "
                f"emit gen_ai.usage.missing instead of attributing"
            )
        self.reconciled[cb.span_id] = "metric_exemplar"
        return "metric_exemplar"

    def sweep_unreconciled(self, now: float) -> list[str]:
        missing = []
        for sid, span in self.spans.items():
            if sid not in self.reconciled and now - span.ended_at > self.usage_timeout_s:
                missing.append(sid)
        return missing
