# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-model-emits-a-tool-call-whose-id-is-replayed-across-a-resumed-agent-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-model-emits-a-tool-call-whose-id-is-replayed-across-a-resumed-agent-run.warrant.json
# Markdown SHA-256:   22d9f4361a28ba57bd553e696aa474e79f6e0f4b5055a5ebb6b7651910122bb6
# Code AST SHA-256:   a856a97c9f4a86f839e703791851ef8306a994da608d559e79dd9ac05d5b82b1
# Verified Classes:   ReplayReconciliationError, ToolCallKey, ExecutionRecord, ExecutionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReplayReconciliationError(RuntimeError):
    """Raised when a resumed agent run would re-dispatch a tool call whose
    (response_id, tool_call_id) already reached a terminal span, or when the
    execution ledger is missing for a non-idempotent pending call."""
    pass


@dataclass(frozen=True)
class ToolCallKey:
    response_id: str          # gen_ai.response.id
    tool_call_id: str         # gen_ai.tool.call.id
    tool_name: str            # gen_ai.tool.name


@dataclass
class ExecutionRecord:
    key: ToolCallKey
    span_id: str
    terminal: bool
    status: str               # "ok" | "error" | "cancelled"
    start_time: datetime
    output: Optional[str] = None


@dataclass
class ExecutionLedger:
    records: dict[ToolCallKey, ExecutionRecord] = field(default_factory=dict)

    def record_terminal(self, rec: ExecutionRecord) -> None:
        existing = self.records.get(rec.key)
        if existing is not None and existing.terminal and existing.status == "ok":
            # A second terminal-ok for the same key is a replay artifact.
            # Keep the first; do not overwrite.
            return
        self.records[rec.key] = rec

    def lookup(self, key: ToolCallKey) -> Optional[ExecutionRecord]:
        return self.records.get(key)


NON_IDEMPOTENT_TOOLS = {"send_email", "create_ticket", "transfer_funds"}


def reconcile_resume(
    pending_calls: list[ToolCallKey],
    ledger: ExecutionLedger,
) -> list[ToolCallKey]:
    """Partition pending calls into those safe to dispatch vs. those that must
    be reconstructed from the ledger. Returns the calls still needing dispatch."""
    to_dispatch: list[ToolCallKey] = []
    for key in pending_calls:
        rec = ledger.lookup(key)
        if rec is None:
            # Never dispatched (or dispatched without a ledger write — unsafe).
            if key.tool_name in NON_IDEMPOTENT_TOOLS:
                raise ReplayReconciliationError(
                    f"No execution ledger entry for non-idempotent tool "
                    f"{key.tool_name!r} call_id={key.tool_call_id!r} "
                    f"under response_id={key.response_id!r}; refusing to "
                    f"re-dispatch, as the call may have partially executed."
                )
            to_dispatch.append(key)
            continue
        if rec.terminal:
            # Already executed; synthesize tool result from ledger, do not re-run.
            continue
        # Dispatched but not terminal (crash mid-execution): ambiguous.
        if key.tool_name in NON_IDEMPOTENT_TOOLS:
            raise ReplayReconciliationError(
                f"Ambiguous state for non-idempotent tool {key.tool_name!r} "
                f"call_id={key.tool_call_id!r}: dispatched at span {rec.span_id} "
                f"but no terminal status. Re-dispatch requires an idempotency "
                f"key derived from (response_id, tool_call_id)."
            )
        to_dispatch.append(key)
    return to_dispatch


def emit_tool_span(
    key: ToolCallKey,
    span_id: str,
    ledger: ExecutionLedger,
    now: datetime,
) -> ExecutionRecord:
    """Emits a tool-call span record, marking replays explicitly so downstream
    aggregation by gen_ai.tool.name does not double-count."""
    existing = ledger.lookup(key)
    is_replay = existing is not None and existing.span_id != span_id
    rec = ExecutionRecord(
        key=key,
        span_id=span_id,
        terminal=False,
        status="running",
        start_time=now,
    )
    if is_replay:
        # gen_ai.tool.call.replay=true attribute must be set on the span.
        rec.status = "replay"
    ledger.records.setdefault(key, rec)
    return rec
