# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-trusting-token-accounting-from-a-resumed-agent-run.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-attributes-before-trusting-token-accounting-from-a-resumed-agent-run.warrant.json
# Markdown SHA-256:   06ff10228122357fde7957674fcace5e24fc84db5d5a367b70ca96ff1934940d
# Code AST SHA-256:   83d149c8cd049965c4585188e4654d795eece083cc5837d3b7e259d547689182
# Verified Classes:   TraceReconciliationError, Checkpoint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceReconciliationError(RuntimeError):
    """Raised when a resumed agent run cannot safely reconcile GenAI spans."""


@dataclass(frozen=True)
class Checkpoint:
    logical_action_id: str          # stable across resume, assigned at plan time
    traceparent: Optional[str]      # W3C traceparent active at checkpoint
    attempt: int                    # 1 for first execution


def reconcile_resume_span(
    checkpoint: Checkpoint,
    emitted_tool_call_id: str,
    emitted_trace_id: str,
) -> dict:
    """
    Enforce the invariant: a resumed run must reuse the checkpoint's logical
    action ID and trace context, or explicitly declare replay-as-new-run.
    """
    if checkpoint.traceparent is None:
        # No trace context in checkpoint -> cannot link; must declare new run.
        raise TraceReconciliationError(
            "checkpoint has no traceparent; refusing silent trace fork"
        )

    # Parse traceparent: version-traceid-spanid-flags
    parts = checkpoint.traceparent.split("-")
    if len(parts) != 4:
        raise TraceReconciliationError(
            f"malformed traceparent in checkpoint: {checkpoint.traceparent!r}"
        )
    checkpoint_trace_id = parts[1]

    if emitted_trace_id != checkpoint_trace_id:
        raise TraceReconciliationError(
            "resumed span emitted under a different trace_id "
            f"({emitted_trace_id} != {checkpoint_trace_id}); "
            "runtime must propagate traceparent from checkpoint"
        )

    if emitted_tool_call_id != checkpoint.logical_action_id:
        raise TraceReconciliationError(
            "resumed span minted a new gen_ai.tool.call.id "
            f"({emitted_tool_call_id} != {checkpoint.logical_action_id}); "
            "tool-call identity must be checkpoint-stable"
        )

    return {
        "gen_ai.tool.call.id": checkpoint.logical_action_id,
        "gen_ai.attempt": checkpoint.attempt,
        "trace_id": emitted_trace_id,
    }


def aggregate_run_cost(spans: list[dict]) -> dict:
    """
    Sum gen_ai.usage.* per logical action, taking the last successful attempt.
    Raises if any span lacks a checkpoint-stable logical ID.
    """
    by_action: dict[str, dict] = {}
    for span in spans:
        action_id = span.get("gen_ai.tool.call.id") or span.get("gen_ai.request.id")
        if action_id is None:
            raise TraceReconciliationError(
                "span lacks logical action ID; cannot de-duplicate retries"
            )
        attempt = span.get("gen_ai.attempt", 1)
        prev = by_action.get(action_id)
        if prev is None or attempt >= prev["gen_ai.attempt"]:
            by_action[action_id] = span

    total_in = sum(s.get("gen_ai.usage.input_tokens", 0) for s in by_action.values())
    total_out = sum(s.get("gen_ai.usage.output_tokens", 0) for s in by_action.values())
    return {
        "logical_actions": len(by_action),
        "input_tokens": total_in,
        "output_tokens": total_out,
    }
