# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-opentelemetry-genai-span-nesting-to-preserve-tool-call-causality.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-opentelemetry-genai-span-nesting-to-preserve-tool-call-causality.warrant.json
# Markdown SHA-256:   c8625a310f6a854dcfad496575e73e755a7854d2eabddf29eb46874a8bcbe89e
# Code AST SHA-256:   639bc461000360371c892e2fd00deb75f33a8ea07c4609c0ec1fd84b193747c0
# Verified Classes:   DanglingParentSpanError, SpanContext, ExecutionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DanglingParentSpanError(RuntimeError):
    """Raised when a tool span would be emitted with a parent that the active tracer cannot resolve."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str


@dataclass
class ExecutionState:
    resumed_from_checkpoint: bool = False
    under_replay: bool = False
    delegation_boundary_crossed: bool = False


def emit_tool_span(
    tool_name: str,
    agent_ctx: Optional[SpanContext],
    active_trace_id: str,
    agent_span_recording: bool,
    state: ExecutionState,
    turn_id: str,
    instance_id: str,
) -> dict:
    nest = (
        agent_ctx is not None
        and agent_span_recording
        and agent_ctx.trace_id == active_trace_id
        and not state.resumed_from_checkpoint
        and not state.under_replay
        and not state.delegation_boundary_crossed
    )

    if nest:
        return {
            "name": f"execute_tool {tool_name}",
            "trace_id": active_trace_id,
            "parent_span_id": agent_ctx.span_id,
            "links": [],
            "attributes": {
                "gen_ai.operation.name": "execute_tool",
                "gen_ai.tool.name": tool_name,
                "gen_ai.agent.turn_id": turn_id,
                "gen_ai.agent.instance_id": instance_id,
            },
        }

    # Non-nestable path: causality must be expressed as a link, never a dangling parent.
    if agent_ctx is not None and agent_ctx.trace_id != active_trace_id:
        # Cross-trace link is legal; cross-trace *parent* is not.
        pass
    elif agent_ctx is not None and agent_ctx.trace_id == active_trace_id:
        # Same trace but parent may be closed/unrecording: link, do not nest.
        pass

    if agent_ctx is None and not state.resumed_from_checkpoint:
        # No agent context at all and not a known resume: this is a genuine bug,
        # not a boundary transition. Refuse to fabricate a root.
        raise DanglingParentSpanError(
            f"tool '{tool_name}' has no agent context and no resume/replay/delegation "
            f"justification; refusing to emit an orphan span"
        )

    return {
        "name": f"execute_tool {tool_name}",
        "trace_id": active_trace_id,
        "parent_span_id": None,
        "links": [agent_ctx] if agent_ctx else [],
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": tool_name,
            "gen_ai.agent.turn_id": turn_id,
            "gen_ai.agent.instance_id": instance_id,
            "gen_ai.causality.mode": "linked",
        },
    }
