# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-finalize-a-genai-agent-span-when-tool-call-attributes-arrive-after-the-parent-span-has-been-marked-no.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-finalize-a-genai-agent-span-when-tool-call-attributes-arrive-after-the-parent-span-has-been-marked-no.warrant.json
# Markdown SHA-256:   a1e26dba5806dcfbfc3410edbb1d01915113918f4915f9f89a348afd73414a17
# Code AST SHA-256:   a0ed9657e260cc0b2ba70880329466ae10586ff66d05689e4c7e18fa6df4fb63
# Verified Classes:   HollowGenAISpanError, ToolCallRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class HollowGenAISpanError(RuntimeError):
    """Raised when a gen_ai.tool.call span is finalized without required attributes."""

    def __init__(self, span_id: str, missing: list[str]):
        self.span_id = span_id
        self.missing = missing
        super().__init__(
            f"gen_ai.tool.call span {span_id} is hollow; missing {missing}"
        )


@dataclass
class ToolCallRecord:
    tool_name: str
    tool_call_id: str
    attributes: dict[str, Any] = field(default_factory=dict)

    REQUIRED = ("gen_ai.tool.name", "gen_ai.tool.call.id")

    def finalize(self, span) -> None:
        if not span.is_recording():
            # Span went non-recording before the tool call finalized.
            # Do not silently drop; surface as a structured log + metric.
            emit_degraded_log(
                trace_id=span.get_span_context().trace_id,
                span_id=span.get_span_context().span_id,
                record=self,
            )
            increment_counter("gen_ai.attribute_after_end")
            return

        span.set_attribute("gen_ai.tool.name", self.tool_name)
        span.set_attribute("gen_ai.tool.call.id", self.tool_call_id)
        for k, v in self.attributes.items():
            span.set_attribute(k, v)
        span.end()


def validate_exported_tool_span(span_dict: dict) -> None:
    """Guardrail run before export: reject hollow gen_ai.tool.call spans."""
    if span_dict.get("name") != "gen_ai.tool.call":
        return
    attrs = span_dict.get("attributes", {})
    missing = [k for k in ToolCallRecord.REQUIRED if k not in attrs]
    if missing:
        raise HollowGenAISpanError(
            span_id=span_dict["context"]["span_id"], missing=missing
        )


def emit_degraded_log(trace_id: int, span_id: int, record: ToolCallRecord) -> None:
    ...


def increment_counter(name: str) -> None:
    ...
