# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attributes-from-silently-diverging-between-agent-emit-sites-and-collector-side-conformance-checks.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-attributes-from-silently-diverging-between-agent-emit-sites-and-collector-side-conformance-checks.warrant.json
# Markdown SHA-256:   9521609b48f08aad009a8470fb322437f656dcfb5d106240160f8de664ca63f6
# Code AST SHA-256:   2a003f11e018147213d96e27ad30548fa0637a607a8fe5f9ca655429e78818dc
# Verified Classes:   GenAISchemaConformanceError, PinnedSchema
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any

class GenAISchemaConformanceError(RuntimeError):
    """Raised when a gen_ai.* span attribute cannot be proven conformant
    against the pinned schema version shared by emitter and collector."""
    pass

@dataclass(frozen=True)
class PinnedSchema:
    version: str
    # canonical type per gen_ai.* key; "int" | "str" | "float"
    types: dict[str, str]

def _coerce(value: Any, canonical: str) -> Any:
    if canonical == "int":
        if isinstance(value, bool):
            raise GenAISchemaConformanceError("bool is not a valid int attribute")
        return int(value)
    if canonical == "float":
        return float(value)
    if canonical == "str":
        return str(value)
    raise GenAISchemaConformanceError(f"unknown canonical type {canonical!r}")

def normalize_and_validate(
    attrs: dict[str, Any],
    schema: PinnedSchema,
    declared_version: str,
) -> dict[str, Any]:
    """Emitter-side: coerce to canonical types, then validate. The returned
    dict is guaranteed to be a fixed point of the collector's coercion
    because both use the same _coerce function and the same schema."""
    if declared_version != schema.version:
        raise GenAISchemaConformanceError(
            f"schema version skew: emitter={declared_version!r} "
            f"collector={schema.version!r}; refusing to emit"
        )
    out: dict[str, Any] = {}
    for key, value in attrs.items():
        if not key.startswith("gen_ai."):
            out[key] = value
            continue
        canonical = schema.types.get(key)
        if canonical is None:
            raise GenAISchemaConformanceError(
                f"attribute {key!r} not in pinned schema {schema.version!r}"
            )
        out[key] = _coerce(value, canonical)
    # fixed-point check: re-coercion must be identity
    for key, value in out.items():
        if key.startswith("gen_ai."):
            canonical = schema.types[key]
            if _coerce(value, canonical) != value:
                raise GenAISchemaConformanceError(
                    f"attribute {key!r} not a fixed point after coercion"
                )
    return out

def emit_tool_span(
    raw_attrs: dict[str, Any],
    schema: PinnedSchema,
    declared_version: str,
) -> dict[str, Any]:
    try:
        return normalize_and_validate(raw_attrs, schema, declared_version)
    except GenAISchemaConformanceError:
        # count the drop keyed on the offending attribute, not a generic error
        raise
