# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-misattribution-across-multi-turn-agent-turns-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-misattribution-across-multi-turn-agent-turns-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   ad8a573625df404b6d8d449cdf87cf8bf2ff106c0a4c2ffdc857fbab25b266d7
# Code AST SHA-256:   938e65d2dc21812aa23bd0675df5e4087cf48676113d57208deaf82d0f0ac31f
# Verified Classes:   ToolCallAttributionError, ChatSpan, ToolCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ToolCallAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be unambiguously attributed to an LLM span."""
    pass


@dataclass(frozen=True)
class ChatSpan:
    span_id: str
    conversation_id: str
    serialized_prompt: str          # full messages array as sent to the model
    finish_reason: str              # "stop", "tool_calls", "length", ...


@dataclass(frozen=True)
class ToolCall:
    tool_call_id: str
    tool_name: str
    parent_llm_span_id: str


def validate_tool_call_attribution(
    tool_call: ToolCall,
    preceding_chat: ChatSpan,
    conversation_id: str,
) -> None:
    if tool_call.parent_llm_span_id != preceding_chat.span_id:
        raise ToolCallAttributionError(
            f"tool call {tool_call.tool_call_id!r} claims parent "
            f"{tool_call.parent_llm_span_id!r} but the immediately preceding "
            f"chat span is {preceding_chat.span_id!r}"
        )
    if preceding_chat.conversation_id != conversation_id:
        raise ToolCallAttributionError(
            f"conversation mismatch: tool call in {conversation_id!r}, "
            f"chat span in {preceding_chat.conversation_id!r}"
        )
    if preceding_chat.finish_reason == "length":
        raise ToolCallAttributionError(
            f"preceding chat span {preceding_chat.span_id!r} was truncated "
            f"(finish_reason=length); tool_call_id {tool_call.tool_call_id!r} "
            f"may be partial and must not be executed"
        )
    if tool_call.tool_call_id not in preceding_chat.serialized_prompt:
        raise ToolCallAttributionError(
            f"tool_call_id {tool_call.tool_call_id!r} does not appear verbatim "
            f"in the preceding chat span's prompt; id was regenerated or "
            f"truncated and cannot be joined to a consuming LLM span"
        )


def emit_tool_span(
    tool_call: ToolCall,
    preceding_chat: Optional[ChatSpan],
    conversation_id: str,
) -> dict:
    if preceding_chat is None:
        raise ToolCallAttributionError(
            f"no preceding chat span recorded for tool call "
            f"{tool_call.tool_call_id!r}; refusing to emit orphan tool span"
        )
    validate_tool_call_attribution(tool_call, preceding_chat, conversation_id)
    return {
        "name": f"execute_tool {tool_call.tool_name}",
        "parent_span_id": preceding_chat.span_id,
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.conversation.id": conversation_id,
            "gen_ai.tool.name": tool_call.tool_name,
            "gen_ai.tool.call.id": tool_call.tool_call_id,
        },
    }
