# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-trace-rather-than-close-it-span-termination-invariants-for-opentelemetry-genai-agent-spans-under-tool-call-attribute-mut.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-trace-rather-than-close-it-span-termination-invariants-for-opentelemetry-genai-agent-spans-under-tool-call-attribute-mut.warrant.json
# Markdown SHA-256:   6fa6d6b4596dd5bd5ab893d04194c6c5fa3bbd9df1b39a829becff206e59a421
# Code AST SHA-256:   200fad7f39264ce8f2019a88fd5498606d743751dfc8899ba7a0e75b5efdd406
# Verified Classes:   SpanTerminationError, ToolSpanStatus, ToolCallSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpanTerminationError(RuntimeError):
    """Raised when a GenAI tool-call span cannot be legally terminated."""


class ToolSpanStatus(Enum):
    OPEN = "open"
    OK = "ok"
    ERROR = "error"


@dataclass
class ToolCallSpan:
    call_id: str
    requested_tool: str
    executed_tool: str
    status: ToolSpanStatus = ToolSpanStatus.OPEN
    result_consumed: bool = False
    supersedes: Optional[str] = None
    duplicate_of: Optional[str] = None
    abandoned: bool = False
    _ended: bool = False
    _attrs: dict = field(default_factory=dict)

    def set_attribute(self, key: str, value) -> None:
        if self._ended:
            # SDK silently drops this; we surface it instead of lying.
            raise SpanTerminationError(
                f"attribute {key!r} written after span end on call {self.call_id!r}"
            )
        self._attrs[key] = value

    def terminate(self, successor: Optional["ToolCallSpan"] = None) -> None:
        if self._ended:
            raise SpanTerminationError(f"span {self.call_id!r} already terminated")
        if not self.call_id:
            raise SpanTerminationError("call_id must be persisted before termination")

        # Boundary rule: consumption, not completion, decides OK vs ERROR.
        if not self.result_consumed and successor is None:
            self.abandoned = True
            self.status = ToolSpanStatus.ERROR
            self.set_attribute("gen_ai.tool.call.abandoned", True)
        elif self.requested_tool != self.executed_tool and successor is None:
            # Identity was invalidated by model output; must abort, not close OK.
            self.status = ToolSpanStatus.ERROR
            self.set_attribute("gen_ai.tool.call.identity_mismatch", True)
        elif successor is not None:
            self.status = ToolSpanStatus.ERROR
            successor.supersedes = self.call_id
            self.set_attribute("gen_ai.tool.call.superseded_by", successor.call_id)
        else:
            self.status = ToolSpanStatus.OK

        self._ended = True


def finalize_tool_span(
    span: ToolCallSpan,
    successor: Optional[ToolCallSpan] = None,
    parent_open: bool = True,
) -> None:
    if not parent_open:
        raise SpanTerminationError(
            f"cannot terminate call {span.call_id!r}: parent invoke_agent span sealed; "
            "emit corrective span as new root with conversation linkage"
        )
    if span._ended:
        raise SpanTerminationError(f"span {span.call_id!r} already ended")
    span.terminate(successor=successor)
