# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-retried-tool-call-double-counts-gen-ai-usage-input-tokens-across-a-resumed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-retried-tool-call-double-counts-gen-ai-usage-input-tokens-across-a-resumed.warrant.json
# Markdown SHA-256:   4abbb3dd9b17a1cfc3381a822bb6192759d4b98cf23d7fa49eb7a4a9849cadb4
# Code AST SHA-256:   e383cf832d0af4c1e4c7449db97ff15005f6c318c79fa4529b459d1b60c2fb18
# Verified Classes:   TraceReconciliationError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceReconciliationError(RuntimeError):
    """Raised when a GenAI trace cannot be reduced to one billed attempt per logical step."""


@dataclass
class GenAISpan:
    span_id: str
    operation: str                      # "chat" | "execute_tool"
    tool_call_id: Optional[str]
    retry_attempt: int
    resume_epoch: int
    billing_status: str                 # "billed" | "phantom" | "unknown"
    input_tokens: int = 0
    output_tokens: int = 0


def reconcile_trace(spans: list[GenAISpan]) -> dict:
    """
    Reduce a trace to one authoritative attempt per (tool_call_id, resume_epoch)
    and return billed token totals. Raises if any logical step is ambiguous.
    """
    groups: dict[tuple, list[GenAISpan]] = {}
    for s in spans:
        key = (s.tool_call_id, s.resume_epoch, s.operation)
        groups.setdefault(key, []).append(s)

    billed_input = 0
    billed_output = 0
    for key, attempts in groups.items():
        terminal_epoch = max(a.resume_epoch for a in attempts)
        terminal = [a for a in attempts if a.resume_epoch == terminal_epoch]

        if any(a.billing_status == "unknown" for a in terminal):
            raise TraceReconciliationError(
                f"cannot reconcile {key}: terminal epoch has unknown billing status; "
                f"collapse would under-count, preserve would over-count"
            )

        # Within the terminal epoch, exactly one attempt should be billed.
        billed = [a for a in terminal if a.billing_status == "billed"]
        if len(billed) != 1:
            raise TraceReconciliationError(
                f"logical step {key} has {len(billed)} billed attempts in terminal "
                f"epoch {terminal_epoch}; expected exactly 1"
            )
        billed_input += billed[0].input_tokens
        billed_output += billed[0].output_tokens

    return {"input_tokens": billed_input, "output_tokens": billed_output}


def verify_tool_success(spans: list[GenAISpan], tool_call_id: str) -> bool:
    """
    A verifier replaying the trace must not accept a failed attempt as
    authoritative when a later epoch succeeded.
    """
    relevant = [s for s in spans if s.tool_call_id == tool_call_id]
    if not relevant:
        raise TraceReconciliationError(f"no spans for tool_call_id={tool_call_id}")

    terminal_epoch = max(s.resume_epoch for s in relevant)
    terminal = [s for s in relevant if s.resume_epoch == terminal_epoch]
    if len({s.billing_status for s in terminal}) > 1:
        raise TraceReconciliationError(
            f"tool_call_id={tool_call_id} has mixed billing statuses in terminal "
            f"epoch {terminal_epoch}; verifier cannot determine success"
        )
    return all(s.billing_status == "billed" for s in terminal)
