# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-a-mutable-tool-call-contract-before-closing-a-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-a-mutable-tool-call-contract-before-closing-a-parent-agent-span.warrant.json
# Markdown SHA-256:   034e91119386d55dc18cd67082c214335f1b4a1b9e821c955a0af433c63f0b17
# Code AST SHA-256:   9421c9e08cc2f181ce8fc864589e2c4de90b172d1c3728ab83e1b609883ab367
# Verified Classes:   TelemetryContractDriftError, ToolCallSpan, ParentAgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class TelemetryContractDriftError(RuntimeError):
    """Raised when a parent agent span cannot be closed with summed usage
    because its child tool spans drifted in schema or call-ID namespace."""
    pass


@dataclass
class ToolCallSpan:
    call_id: str
    tool_name: str
    schema_version: str
    input_tokens: int
    output_tokens: int
    retry_attempt: int = 0


@dataclass
class ParentAgentSpan:
    span_id: str
    declared_tool_schemas: dict  # tool_name -> schema_version
    children: list = field(default_factory=list)
    usage_attributable: bool = True
    degraded: bool = False


def register_child(parent: ParentAgentSpan, child: ToolCallSpan) -> None:
    if child.call_id in {c.call_id for c in parent.children}:
        # Same call-id reused across a retry or across instances: the collector
        # will deduplicate and one span will vanish. Force a distinct id.
        raise TelemetryContractDriftError(
            f"call_id collision on {child.call_id!r} for tool {child.tool_name!r}; "
            f"regenerate with uuid7() before appending"
        )
    parent.children.append(child)


def close_parent_span(parent: ParentAgentSpan) -> ParentAgentSpan:
    seen_schemas = {c.tool_name: c.schema_version for c in parent.children}
    drifted = {
        name: ver
        for name, ver in seen_schemas.items()
        if parent.declared_tool_schemas.get(name) != ver
    }
    if drifted:
        # Cannot attribute summed usage to a single contract.
        parent.usage_attributable = False
        parent.degraded = True
        # Emit gen_ai.tool.schema_drift event span here; do NOT raise, because
        # the agent loop itself succeeded — only telemetry is degraded.
    return parent


def emit_usage(parent: ParentAgentSpan) -> dict:
    if not parent.usage_attributable:
        raise TelemetryContractDriftError(
            f"parent span {parent.span_id!r} is schema-drifted; "
            f"refusing to emit gen_ai.usage.* attributes (would mis-attribute "
            f"tokens across {len(parent.children)} child tool spans)"
        )
    return {
        "gen_ai.usage.input_tokens": sum(c.input_tokens for c in parent.children),
        "gen_ai.usage.output_tokens": sum(c.output_tokens for c in parent.children),
    }


def uuid7() -> str:
    return str(uuid.uuid4())  # stand-in; real impl is time-ordered
