# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-parent-child-span-linkage-when-an-agent-span-is-exported-after-its-tool-call-children-close-under-opentelemetry-genai-semant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-parent-child-span-linkage-when-an-agent-span-is-exported-after-its-tool-call-children-close-under-opentelemetry-genai-semant.warrant.json
# Markdown SHA-256:   5409e93d70e5637b37aea8ae1d1ee9274cab99cbd80b365e70c491a339dcb333
# Code AST SHA-256:   b569bff049ffcc21afb05cc015e8c0bd81d94a023bb6540aacbf98d4c7538f6d
# Verified Classes:   SpanLinkageError, Span, TraceRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class SpanLinkageError(RuntimeError):
    """Raised when a GenAI span's parent linkage cannot be satisfied."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    start_time: float
    end_time: Optional[float] = None
    attributes: Dict[str, str] = field(default_factory=dict)


class TraceRegistry:
    """In-memory stand-in for a trace backend that joins on parent_span_id."""

    def __init__(self) -> None:
        self._spans: Dict[str, Span] = {}

    def ingest(self, span: Span) -> None:
        if span.span_id in self._spans:
            raise SpanLinkageError(
                f"span_id collision: {span.span_id} already present in trace "
                f"{self._spans[span.span_id].trace_id}; refusing silent mis-join"
            )
        self._spans[span.span_id] = span

    def validate_linkage(self, child: Span) -> None:
        if child.parent_span_id is None:
            return
        parent = self._spans.get(child.parent_span_id)
        if parent is None:
            raise SpanLinkageError(
                f"orphan: {child.operation} span {child.span_id} references "
                f"parent {child.parent_span_id} not present in trace {child.trace_id}"
            )
        if parent.trace_id != child.trace_id:
            raise SpanLinkageError(
                f"cross-trace link: {child.span_id} -> {parent.span_id}"
            )
        if parent.start_time > child.start_time:
            raise SpanLinkageError(
                f"temporal inversion: parent {parent.span_id} starts "
                f"{parent.start_time} after child {child.span_id} starts {child.start_time}"
            )
        if parent.end_time is not None and parent.end_time < child.end_time:
            raise SpanLinkageError(
                f"parent {parent.span_id} ends before child {child.span_id}"
            )


def export_tool_call(
    registry: TraceRegistry,
    trace_id: str,
    parent_span_id: str,
    tool_name: str,
    duration_ms: int = 40,
) -> Span:
    now = time.monotonic()
    child = Span(
        trace_id=trace_id,
        span_id=f"t-{tool_name}-{int(now * 1000)}",
        parent_span_id=parent_span_id,
        operation="execute_tool",
        start_time=now,
        end_time=now + duration_ms / 1000.0,
        attributes={
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": tool_name,
        },
    )
    registry.ingest(child)
    registry.validate_linkage(child)
    return child


def resume_agent_span(
    registry: TraceRegistry,
    trace_id: str,
    checkpointed_span_id: Optional[str],
) -> Span:
    if checkpointed_span_id is None:
        raise SpanLinkageError(
            "checkpoint did not persist open agent span_id; resume would mint a "
            "new identity and orphan previously-exported tool-call children"
        )
    existing = registry._spans.get(checkpointed_span_id)
    if existing is not None:
        return existing
    span = Span(
        trace_id=trace_id,
        span_id=checkpointed_span_id,
        parent_span_id=None,
        operation="invoke_agent",
        start_time=time.monotonic(),
        attributes={"gen_ai.operation.name": "invoke_agent"},
    )
    registry.ingest(span)
    return span
