# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-miscount-tokens-when-opentelemetry-genai-span-accounting-diverges-across-a-resumed-agent-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-miscount-tokens-when-opentelemetry-genai-span-accounting-diverges-across-a-resumed-agent-turn.warrant.json
# Markdown SHA-256:   1af09fe5f360a67c616737a06a4b8e3b030807e5a8d9effe3da24e09fc3ac11a
# Code AST SHA-256:   38683bf96ef78d8cf8786c83f65fafc6a6291984045bbb5c99abcb68e73cab5f
# Verified Classes:   TurnAccountingError, GenAISpan, TurnLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TurnAccountingError(RuntimeError):
    """Raised when a resumed agent turn cannot be reconciled to a single token total."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    turn_id: Optional[str]
    input_tokens: int = 0
    output_tokens: int = 0
    replayed_history_tokens: int = 0  # tokens re-sent to reconstruct context on resume
    is_root: bool = False


@dataclass
class TurnLedger:
    spans: list[GenAISpan] = field(default_factory=list)

    def add(self, span: GenAISpan) -> None:
        self.spans.append(span)

    def reconcile_turn(self, turn_id: str) -> tuple[int, int]:
        """Return (true_input, true_output) for a logical turn.

        Requires every span in the turn to carry the same turn_id. Sums all
        gen_ai.chat spans in the turn and subtracts replayed history so that
        context re-sent on resume is not double-counted.
        """
        turn_spans = [s for s in self.spans if s.turn_id == turn_id]
        if not turn_spans:
            raise TurnAccountingError(f"no spans found for turn_id={turn_id!r}")

        roots = [s for s in turn_spans if s.is_root]
        if len(roots) > 1:
            # Multiple roots for one turn means a mid-turn resume produced a
            # disconnected tree. This is only safe if the turn_id is shared;
            # otherwise the pre-pause consumption is unrecoverable.
            pass

        true_input = sum(s.input_tokens for s in turn_spans) - sum(
            s.replayed_history_tokens for s in turn_spans
        )
        true_output = sum(s.output_tokens for s in turn_spans)

        if true_input < 0:
            raise TurnAccountingError(
                f"replay deduction exceeded reported input for turn {turn_id!r}; "
                "replayed_history_tokens likely mis-attributed across spans"
            )
        return true_input, true_output


def emit_resumed_root(
    ledger: TurnLedger,
    pre_pause_trace_id: str,
    turn_id: str,
    new_trace_id: str,
) -> GenAISpan:
    """Emit a root for a resumed worker, linking back to the pre-pause trace.

    Refuses to emit if the turn_id is absent, because an unlinked root cannot
    be reconciled and will silently under-count the logical turn.
    """
    if not turn_id:
        raise TurnAccountingError(
            "resumed root requires a stable turn_id; without it the pre-pause "
            "span tree cannot be joined and token totals will diverge"
        )
    span = GenAISpan(
        span_id=hashlib.sha1(f"{new_trace_id}:root".encode()).hexdigest()[:16],
        trace_id=new_trace_id,
        parent_span_id=None,
        turn_id=turn_id,
        is_root=True,
    )
    ledger.add(span)
    return span
