# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-orphaned-genai-tool-call-spans-before-exporting-them-under-opentelemetry-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-orphaned-genai-tool-call-spans-before-exporting-them-under-opentelemetry-semantic-conventions.warrant.json
# Markdown SHA-256:   7a5397c5c3d7a5803d7fb9df77acba13f7c7e4e3a64f13f89b07d20a64261389
# Code AST SHA-256:   e9650d127129eb46a3c8b903b586804b8d3280d6a5ec89a4e32db834f7b626e1
# Verified Classes:   OrphanedToolSpanError, ParentState, SpanRegistry, ToolSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool span cannot be linked to a live or re-parentable parent."""


class ParentState(Enum):
    UNEXPORTED = "unexported"      # parent in local registry, not yet flushed
    EXPORTED = "exported"          # parent already shipped in a prior batch
    NEVER_SEEN = "never_seen"      # parent absent from registry and export log


@dataclass
class SpanRegistry:
    unexported: set[str] = field(default_factory=set)
    exported: set[str] = field(default_factory=set)

    def state_of(self, span_id: str) -> ParentState:
        if span_id in self.unexported:
            return ParentState.UNEXPORTED
        if span_id in self.exported:
            return ParentState.EXPORTED
        return ParentState.NEVER_SEEN


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    tool_call_id: str
    orphan_reason: str | None = None


def reconcile_before_export(
    span: ToolSpan,
    registry: SpanRegistry,
    invocation_span_id: str,
    allow_dangling_for_collector: bool = False,
) -> ToolSpan:
    """Resolve parent linkage before the OTLP batch is sealed.

    Invariant: an execute_tool span must reference a parent still open at
    export time, or be explicitly re-parented to the invocation span.
    """
    if not span.parent_span_id:
        raise OrphanedToolSpanError(
            f"tool span {span.span_id} has no parent_span_id; "
            f"gen_ai.tool.call.id={span.tool_call_id} cannot be attributed"
        )

    state = registry.state_of(span.parent_span_id)

    if state is ParentState.UNEXPORTED:
        return span  # parent ships in same batch; ordering irrelevant

    if state is ParentState.EXPORTED:
        if allow_dangling_for_collector:
            span.orphan_reason = "parent_premature_export"
            return span
        span.parent_span_id = invocation_span_id
        span.orphan_reason = "parent_premature_export"
        return span

    # NEVER_SEEN: parent lost across a process/checkpoint boundary
    if invocation_span_id is None:
        raise OrphanedToolSpanError(
            f"tool span {span.span_id} orphaned (parent {span.parent_span_id} "
            f"never seen) and no invocation span available for re-parenting"
        )
    span.parent_span_id = invocation_span_id
    span.orphan_reason = "parent_never_seen"
    return span
