# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-span-parenting-when-a-tool-call-child-span-s-gen-ai-tool-call-id-does-not-resolve-to-a-p.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-span-parenting-when-a-tool-call-child-span-s-gen-ai-tool-call-id-does-not-resolve-to-a-p.warrant.json
# Markdown SHA-256:   13e27874a3b75305ac263ab5b57b6b1bba0bb29c4625a7d10bf88d5a7bb0154c
# Code AST SHA-256:   02f5b6e6ac45e8d39bda70fc450090eb29a9bc905da9ac6e69be0421cf456da0
# Verified Classes:   ToolCallSpanParentingError, SpanRef, ToolSpanRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ToolCallSpanParentingError(RuntimeError):
    """Raised when an execute_tool span would violate the call-id/trace invariant."""


@dataclass
class SpanRef:
    trace_id: str
    span_id: str
    operation_name: str
    call_id: Optional[str] = None
    attempt: int = 0


class ToolSpanRegistry:
    """Tracks execute_tool spans per trace to enforce the call-id invariant."""

    def __init__(self) -> None:
        # (trace_id, call_id) -> list of (span_id, attempt, status)
        self._spans: dict[tuple[str, str], list[tuple[str, int, str]]] = {}

    def register(
        self,
        parent: SpanRef,
        call_id: str,
        attempt: int = 0,
        reassigned: bool = False,
    ) -> None:
        if parent.operation_name != "execute_tool":
            raise ToolCallSpanParentingError(
                f"result span for call_id={call_id!r} parented to "
                f"{parent.operation_name!r} (trace {parent.trace_id}); "
                f"must parent to an execute_tool span"
            )

        key = (parent.trace_id, call_id)
        existing = self._spans.get(key, [])

        # Cross-trace reuse: call id already seen in a *different* trace.
        for (other_trace, other_call), spans in self._spans.items():
            if other_call == call_id and other_trace != parent.trace_id and spans:
                if not reassigned:
                    raise ToolCallSpanParentingError(
                        f"call_id={call_id!r} already bound to trace "
                        f"{other_trace}; cross-trace reuse requires "
                        f"reassigned=True"
                    )

        # Same-trace duplicate without attempt increment.
        if existing:
            last_attempt, last_status = existing[-1][1], existing[-1][2]
            if attempt <= last_attempt and last_status != "error":
                raise ToolCallSpanParentingError(
                    f"duplicate execute_tool span for call_id={call_id!r} "
                    f"in trace {parent.trace_id} without attempt increment "
                    f"(last attempt={last_attempt}, status={last_status})"
                )

        self._spans.setdefault(key, []).append(
            (parent.span_id, attempt, "pending")
        )

    def close(self, trace_id: str, call_id: str, span_id: str, status: str) -> None:
        key = (trace_id, call_id)
        spans = self._spans.get(key, [])
        for i, (sid, attempt, _) in enumerate(spans):
            if sid == span_id:
                spans[i] = (sid, attempt, status)
                return
        raise ToolCallSpanParentingError(
            f"close() for unknown span {span_id} on call_id={call_id!r}"
        )
