# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-genai-span-attribute-be-resolved-the-tool-call-argument-cardinality-invariant-in-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-genai-span-attribute-be-resolved-the-tool-call-argument-cardinality-invariant-in-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   0444d61d82b4f98d292d86d9a5e5ee8299c0e3638cdb5212fdb10e65afd0f7aa
# Code AST SHA-256:   58851577e791faa15e605a9db7becd0f1d99b00a0b52c4839cd9ad87403c84e4
# Verified Classes:   ToolCallResolutionError, ProposedToolCall, GenAiSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

"""Guard: enforce the tool-call instance-resolution invariant on a GenAI span."""

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


class ToolCallResolutionError(RuntimeError):
    """Raised when a GenAI span cannot resolve the instance of a tool call."""


@dataclass
class ProposedToolCall:
    call_id: str
    arguments: str  # raw, possibly malformed


@dataclass
class GenAiSpan:
    operation_name: str
    attributes: dict[str, Any] = field(default_factory=dict)
    proposed_calls: list[ProposedToolCall] = field(default_factory=list)


def finalize_inference_span(
    span: GenAiSpan,
    proposed_calls: list[ProposedToolCall],
    call_ids_seen_in_attempt: set[str],
) -> GenAiSpan:
    """Resolve each tool-call instance onto the inference span at close time.

    Enforces:
      * one attribute pair per proposed call (no silent collapse to scalar)
      * call ids unique within the attempt (retry-safe scoping)
      * malformed arguments quarantined, never written to canonical attribute
    """
    if span.operation_name not in ("chat", "text_completion"):
        raise ToolCallResolutionError(
            f"tool-call attributes only valid on inference spans, got {span.operation_name!r}"
        )

    ids = [c.call_id for c in proposed_calls]
    if len(ids) != len(set(ids)):
        raise ToolCallResolutionError(
            f"duplicate tool call ids within one inference attempt: {ids}"
        )

    collisions = set(ids) & call_ids_seen_in_attempt
    if collisions:
        raise ToolCallResolutionError(
            f"tool call ids reused across attempts (retry scoping violated): {collisions}"
        )

    span.attributes["gen_ai.tool.call.count"] = len(proposed_calls)

    for idx, call in enumerate(proposed_calls):
        try:
            json.loads(call.arguments)
        except json.JSONDecodeError:
            # Quarantine: do not emit malformed payload under canonical name.
            span.attributes[f"gen_ai.tool.call.{idx}.arguments.raw"] = call.arguments
            span.attributes[f"gen_ai.tool.call.{idx}.arguments.valid"] = False
            continue
        span.attributes[f"gen_ai.tool.call.{idx}.id"] = call.call_id
        span.attributes[f"gen_ai.tool.call.{idx}.arguments"] = call.arguments
        span.attributes[f"gen_ai.tool.call.{idx}.arguments.valid"] = True

    return span


def assert_proposed_executed_balance(
    span: GenAiSpan, executed_tool_span_ids: set[str]
) -> None:
    """Detect dispatch failures: proposed calls with no matching tool span."""
    proposed = span.attributes.get("gen_ai.tool.call.count", 0)
    if proposed != len(executed_tool_span_ids):
        raise ToolCallResolutionError(
            f"proposed={proposed} executed={len(executed_tool_span_ids)}: "
            "dispatch failure or dropped tool span"
        )
