# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-a-tool-call-event-stream-that-was-truncated-by-the-exp.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-a-tool-call-event-stream-that-was-truncated-by-the-exp.warrant.json
# Markdown SHA-256:   b6cd39b54f4cbb4fe34a7f68772524a65b75f87c54da1f581ac31f960fd0616f
# Code AST SHA-256:   c271d887a02e6c0822ac31f14dead064674021974d194bb72b3af03524290fd0
# Verified Classes:   TokenReconciliationError, SpanRecord, EventRecord, RunReconciliation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TokenReconciliationError(RuntimeError):
    """Raised when a run's span set and event stream cannot be reconciled
    into a single causally complete, non-double-counted token total."""
    pass


@dataclass
class SpanRecord:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str          # "invoke_agent" | "chat" | "execute_tool"
    end_time: float
    output_tokens: int


@dataclass
class EventRecord:
    trace_id: str
    seq: int
    kind: str               # "tool_call" | "tool_result" | "chat_turn"
    span_id: Optional[str]  # span that should annotate this event, if any


@dataclass
class RunReconciliation:
    trace_id: str
    status: str             # "complete" | "degraded" | "incomplete"
    billed_output_tokens: int
    unattributed_tokens: int
    missing_events: int = 0


def reconcile_run(
    trace_id: str,
    spans: list[SpanRecord],
    events: list[EventRecord],
    now: float,
    schedule_delay_millis: int = 5000,
    export_timeout_millis: int = 30000,
    clock_skew_margin_millis: int = 2000,
) -> RunReconciliation:
    gate = (schedule_delay_millis + export_timeout_millis + clock_skew_margin_millis) / 1000.0

    run_spans = [s for s in spans if s.trace_id == trace_id]
    run_events = sorted((e for e in events if e.trace_id == trace_id), key=lambda e: e.seq)

    if not run_events:
        raise TokenReconciliationError(
            f"trace {trace_id}: no event-stream records; cannot anchor causal spine"
        )

    if not run_spans:
        return RunReconciliation(trace_id, "incomplete", 0, 0, missing_events=len(run_events))

    max_end = max(s.end_time for s in run_spans)
    if now - max_end < gate:
        raise TokenReconciliationError(
            f"trace {trace_id}: quiescence gate not met "
            f"({now - max_end:.1f}s < {gate:.1f}s); parent may still be in a later batch"
        )

    parents = [s for s in run_spans if s.operation == "invoke_agent"]
    children = [s for s in run_spans if s.operation in ("chat", "execute_tool")]

    span_ids = {s.span_id for s in run_spans}
    event_span_ids = {e.span_id for e in run_events if e.span_id is not None}
    missing_events = len(event_span_ids - span_ids)

    if not parents:
        # Orphaned children: bill only confirmed children, mark incomplete.
        billed = sum(c.output_tokens for c in children)
        return RunReconciliation(trace_id, "incomplete", billed, 0, missing_events)

    parent = parents[0]
    covered = {c.parent_span_id for c in children if c.parent_span_id == parent.span_id}
    child_coverage = len(covered) / max(len(event_span_ids), 1)

    if child_coverage >= 1.0 and missing_events == 0:
        # Parent aggregate already includes children; do not sum on top.
        return RunReconciliation(trace_id, "complete", parent.output_tokens, 0, 0)

    # Partial child coverage: trust parent, expose residual as unattributed.
    confirmed_child_tokens = sum(
        c.output_tokens for c in children if c.parent_span_id == parent.span_id
    )
    unattributed = max(parent.output_tokens - confirmed_child_tokens, 0)
    if missing_events > 0 and unattributed == 0:
        raise TokenReconciliationError(
            f"trace {trace_id}: {missing_events} events lack spans but parent "
            f"shows no residual; span/event join key is likely broken "
            f"(check traceparent propagation into tool sandbox)"
        )
    return RunReconciliation(
        trace_id, "degraded", parent.output_tokens, unattributed, missing_events
    )
