# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-that-violate-the-otel-semantic-conventions-cardinality-contract-mid-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-that-violate-the-otel-semantic-conventions-cardinality-contract-mid-trace.warrant.json
# Markdown SHA-256:   da3b18313febce3fe58f87e260c94a55795cedc5b29e057df329f103a726e60c
# Code AST SHA-256:   0edee8350470cff8fa54a3ce621376e9ba2b67b6bff188994a24f54d07438882
# Verified Classes:   GenAISpanCardinalityError, GenAISpanGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class GenAISpanCardinalityError(RuntimeError):
    """Raised when a span would violate the OTel GenAI cardinality contract:
    one span must represent exactly one model invocation or tool execution,
    and gen_ai.* attributes must describe that single unit only.
    """


@dataclass
class GenAISpanGuard:
    operation_name: str
    model: str
    _call_count: int = 0
    _finish_reasons: list[str] = field(default_factory=list)
    _input_tokens: int = 0
    _output_tokens: int = 0
    _response_models: set[str] = field(default_factory=set)

    def record_call(
        self,
        *,
        response_model: str,
        finish_reason: str,
        input_tokens: int,
        output_tokens: int,
    ) -> None:
        self._call_count += 1
        self._finish_reasons.append(finish_reason)
        self._input_tokens += input_tokens
        self._output_tokens += output_tokens
        self._response_models.add(response_model)

        # Contract check: a span may describe exactly one call.
        if self._call_count > 1:
            raise GenAISpanCardinalityError(
                f"Span for operation={self.operation_name!r} model={self.model!r} "
                f"recorded {self._call_count} model calls. Retries/fallbacks/fan-out "
                f"must be emitted as child spans, not merged into one span; "
                f"merged usage={self._input_tokens}in/{self._output_tokens}out "
                f"and finish_reasons={self._finish_reasons} would launder "
                f"per-attempt terminations and misattribute cost."
            )

    def assert_single_response_model(self) -> None:
        if len(self._response_models) > 1:
            raise GenAISpanCardinalityError(
                f"Span for operation={self.operation_name!r} observed multiple "
                f"response models {sorted(self._response_models)}. A single span "
                f"cannot carry a scalar gen_ai.response.model; split the fan-out "
                f"into child spans per model."
            )

    def build_attributes(self) -> dict[str, Any]:
        self.assert_single_response_model()
        if self._call_count != 1:
            raise GenAISpanCardinalityError(
                f"Span for operation={self.operation_name!r} has {self._call_count} "
                f"calls; refusing to emit gen_ai.* attributes for a span that does "
                f"not represent exactly one invocation."
            )
        return {
            "gen_ai.operation.name": self.operation_name,
            "gen_ai.request.model": self.model,
            "gen_ai.response.model": next(iter(self._response_models)),
            "gen_ai.response.finish_reasons": list(self._finish_reasons),
            "gen_ai.usage.input_tokens": self._input_tokens,
            "gen_ai.usage.output_tokens": self._output_tokens,
        }


def emit_chat_span(guard: GenAISpanGuard, attempts: list[dict[str, Any]]) -> dict[str, Any]:
    """Emit attributes for a chat span from a list of raw attempts.

    The guard forces one-attempt-per-span; callers that pass multiple attempts
    get a cardinality error and must restructure to child spans.
    """
    for attempt in attempts:
        guard.record_call(
            response_model=attempt["response_model"],
            finish_reason=attempt["finish_reason"],
            input_tokens=attempt["input_tokens"],
            output_tokens=attempt["output_tokens"],
        )
    return guard.build_attributes()
