# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-for-a-tool-call-whose-response-is-truncated-by-the-model-s-own-token-budget-the-gen-ai-compl.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-for-a-tool-call-whose-response-is-truncated-by-the-model-s-own-token-budget-the-gen-ai-compl.warrant.json
# Markdown SHA-256:   97bfb99740f2e6c845e708ac0edc807a383337119c0d98924c0cac3a20b2bd7e
# Code AST SHA-256:   283e20cdbc781bda686643baa4b5f61229bfb9c6f26eb56c901ff7924cd437a5
# Verified Classes:   TruncatedToolCallError, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Any, Mapping

VALID_TERMINAL_FINISH_REASONS = frozenset({"tool_calls", "stop"})


class TruncatedToolCallError(RuntimeError):
    """Raised when a GenAI span's tool_calls entry is not a complete, executable call.

    Triggered when finish_reason is a non-terminal discriminator (e.g. "length")
    or when the arguments JSON string fails to parse. Either condition means the
    tool call was emitted but never validly completed, and must be quarantined
    from replay / distillation / re-execution pipelines.
    """


@dataclass(frozen=True)
class ToolCall:
    id: str
    name: str
    arguments: str


def extract_executable_tool_calls(span_attributes: Mapping[str, Any]) -> list[ToolCall]:
    """Admission check for replay consumers.

    Enforces the invariant: finish_reason gates tool_calls validity.
    Raises TruncatedToolCallError on any violation; never repairs, never
    silently drops, never returns a partial call.
    """
    finish_reason = span_attributes.get("gen_ai.completion.0.finish_reason")
    if finish_reason not in VALID_TERMINAL_FINISH_REASONS:
        if "gen_ai.completion.0.message.tool_calls.0.id" in span_attributes:
            raise TruncatedToolCallError(
                f"tool_calls present under non-terminal finish_reason="
                f"{finish_reason!r}; span records a truncated call, not an "
                f"executable one"
            )
        return []

    calls: list[ToolCall] = []
    index = 0
    while True:
        prefix = f"gen_ai.completion.0.message.tool_calls.{index}"
        call_id = span_attributes.get(f"{prefix}.id")
        if call_id is None:
            break
        name = span_attributes.get(f"{prefix}.function.name")
        raw_args = span_attributes.get(f"{prefix}.function.arguments", "")
        try:
            json.loads(raw_args)
        except json.JSONDecodeError as exc:
            raise TruncatedToolCallError(
                f"tool call {call_id!r} ({name!r}) has unparseable arguments "
                f"despite finish_reason={finish_reason!r}; arguments prefix="
                f"{raw_args[:64]!r}..."
            ) from exc
        calls.append(ToolCall(id=call_id, name=name, arguments=raw_args))
        index += 1
    return calls
