# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-an-agent-span-when-the-otel-genai-gen-ai-operation-name-and-the-emitted-gen-ai-tool-call-id-disagree-across-a-r.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-an-agent-span-when-the-otel-genai-gen-ai-operation-name-and-the-emitted-gen-ai-tool-call-id-disagree-across-a-r.warrant.json
# Markdown SHA-256:   cb08ad312e7a2c818afac795dbb7b32d5b804f00bb63d3c4934e58a10cbd5996
# Code AST SHA-256:   1fb5eb5cb1f597653dc432b8283a83813f8f5152966cc7f6ef3f0675e00ff75f
# Verified Classes:   SpanContinuityError, OperationName, CheckpointedCall, ResumedSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from enum import Enum


class SpanContinuityError(RuntimeError):
    """Raised when a resumed agent span cannot prove it continues a recorded execution."""


class OperationName(str, Enum):
    CHAT = "chat"
    EXECUTE_TOOL = "execute_tool"
    INVOKE_AGENT = "invoke_agent"


@dataclass(frozen=True)
class CheckpointedCall:
    trace_id: str
    tool_call_id: str          # runtime-minted, immutable, stored in the message block
    operation_name: OperationName
    span_closed: bool


@dataclass
class ResumedSpan:
    trace_id: str
    tool_call_id: str
    operation_name: OperationName
    links: list[str] = field(default_factory=list)


def resolve_resume_span(
    checkpointed: CheckpointedCall | None,
    model_emitted_call_id: str,
) -> ResumedSpan:
    """
    Decide how to emit the post-resume span.

    The model_emitted_call_id is a HINT. The checkpoint is authoritative.
    """
    if checkpointed is None:
        # No checkpoint: this is a fresh execution, emit normally under a new trace.
        return ResumedSpan(
            trace_id=str(uuid.uuid4()),
            tool_call_id=model_emitted_call_id,
            operation_name=OperationName.EXECUTE_TOOL,
        )

    same_id = model_emitted_call_id == checkpointed.tool_call_id

    if same_id and checkpointed.span_closed:
        # Verbatim replay, pre-checkpoint span properly closed: continue in place.
        return ResumedSpan(
            trace_id=checkpointed.trace_id,
            tool_call_id=checkpointed.tool_call_id,
            operation_name=OperationName.EXECUTE_TOOL,
        )

    if same_id and not checkpointed.span_closed:
        # Orphaned pre-checkpoint span. Do NOT reuse the join key verbatim:
        # dedup backends would merge and lose the end timestamp.
        return ResumedSpan(
            trace_id=checkpointed.trace_id,
            tool_call_id=f"{checkpointed.tool_call_id}#resume",
            operation_name=OperationName.EXECUTE_TOOL,
        )

    # Re-derivation: model produced a new call id. This is a NEW logical execution.
    # It must not join the original trace's span tree as a child.
    if checkpointed.span_closed is False:
        # We also have an orphan to repair; refuse to silently drop it.
        raise SpanContinuityError(
            f"re-derivation under trace {checkpointed.trace_id} with orphaned span "
            f"{checkpointed.tool_call_id}; repair record required before emitting "
            f"linked execution {model_emitted_call_id}"
        )

    return ResumedSpan(
        trace_id=str(uuid.uuid4()),
        tool_call_id=model_emitted_call_id,
        operation_name=OperationName.EXECUTE_TOOL,
        links=[checkpointed.trace_id],
    )


def emit_span(checkpointed: CheckpointedCall | None, model_emitted_call_id: str) -> dict:
    span = resolve_resume_span(checkpointed, model_emitted_call_id)
    if span.operation_name == OperationName.EXECUTE_TOOL and not span.tool_call_id:
        raise SpanContinuityError("execute_tool span emitted without a tool.call.id")
    return {
        "trace_id": span.trace_id,
        "gen_ai.operation.name": span.operation_name.value,
        "gen_ai.tool.call.id": span.tool_call_id,
        "links": span.links,
    }
