# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-an-opentelemetry-genai-span-for-a-tool-call-that-never-resolves-the-orphaned-span-invariant-and-its-silent-corrupt.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-an-opentelemetry-genai-span-for-a-tool-call-that-never-resolves-the-orphaned-span-invariant-and-its-silent-corrupt.warrant.json
# Markdown SHA-256:   640348eee8896f6bed07ffd77c9e8e1c0aad56f77195a74cae6aa11d17bb5fec
# Code AST SHA-256:   91376345df36184d4421a4a060f8397635985f317dbae50ac1ca48760226b9ce
# Verified Classes:   OrphanedToolSpanError, GenAIToolSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span is closed without a terminal status,
    or when a trace joiner is asked to treat an orphan as completed."""
    pass


@dataclass
class GenAIToolSpan:
    tool_name: str
    call_id: str
    start_ns: int
    end_ns: Optional[int] = None
    status_code: Optional[str] = None  # "OK" | "ERROR" | None (orphan)
    error_type: Optional[str] = None

    def close(self, status_code: str, error_type: Optional[str] = None) -> None:
        if status_code not in ("OK", "ERROR"):
            raise OrphanedToolSpanError(
                f"invalid terminal status {status_code!r} for call {self.call_id}"
            )
        if self.end_ns is not None:
            raise OrphanedToolSpanError(
                f"double-close of tool span {self.call_id}"
            )
        self.end_ns = time.time_ns()
        self.status_code = status_code
        self.error_type = error_type

    @property
    def is_terminal(self) -> bool:
        return self.end_ns is not None and self.status_code in ("OK", "ERROR")


def join_chat_to_tool(
    chat_call_id: str,
    spans_by_call_id: dict[str, list[GenAIToolSpan]],
) -> GenAIToolSpan:
    candidates = spans_by_call_id.get(chat_call_id, [])
    if not candidates:
        raise OrphanedToolSpanError(
            f"no tool span found for call_id {chat_call_id}"
        )
    terminal = [s for s in candidates if s.is_terminal]
    if not terminal:
        # The critical guard: presence is not completion.
        raise OrphanedToolSpanError(
            f"tool call {chat_call_id} has {len(candidates)} span(s) but none "
            f"terminal; refusing to treat orphan as completed tool call"
        )
    if len(terminal) > 1:
        raise OrphanedToolSpanError(
            f"tool call {chat_call_id} has {len(terminal)} terminal spans; "
            f"call_id reused across retries — cannot join deterministically"
        )
    return terminal[0]


def close_span_on_cancellation(span: GenAIToolSpan, exc: BaseException) -> None:
    """Must be called from a finally block; the whole point is that the
    happy path is not the only path that closes the span."""
    if span.is_terminal:
        return
    if isinstance(exc, (TimeoutError,)):
        span.close("ERROR", error_type="timeout")
    elif isinstance(exc, BaseException):
        span.close("ERROR", error_type=type(exc).__name__)
    else:
        raise OrphanedToolSpanError(
            f"close_span_on_cancellation called with no exception for {span.call_id}"
        )
