# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-loss-during-opentelemetry-genai-semantic-convention-export-from-mid-flight-agent-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-loss-during-opentelemetry-genai-semantic-convention-export-from-mid-flight-agent-turns.warrant.json
# Markdown SHA-256:   403c7145ea027999af95e1ae482d7c375a76e9b9bbab80a9fc719a3d1f0643e9
# Code AST SHA-256:   117d2e45c2d36ef54c98ea06bb5e48777f7d0eceee80b163cd05d1d219237371
# Verified Classes:   GenAISpanAttributeLoss, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAISpanAttributeLoss(RuntimeError):
    """Raised when a GenAI span is ended before its terminal attributes resolve."""
    pass


@dataclass
class GenAISpan:
    operation_name: str
    attributes: dict = field(default_factory=dict)
    ended: bool = False

    def set_attribute(self, key: str, value) -> None:
        if self.ended:
            # SDK silently discards; we surface it instead.
            raise GenAISpanAttributeLoss(
                f"attempted to set {key!r} after span.end(); value would be lost"
            )
        self.attributes[key] = value

    def end(self) -> None:
        self.ended = True


REQUIRED_BY_OPERATION = {
    "chat": {
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.output_tokens",
        "gen_ai.response.finish_reasons",
    },
}


def finalize_chat_span(
    span: GenAISpan,
    usage: Optional[dict],
    finish_reasons: Optional[list],
) -> None:
    """Assign terminal attributes, then end. Refuses to end incomplete spans."""
    if span.ended:
        raise GenAISpanAttributeLoss("span already ended before finalize")

    if usage is None or finish_reasons is None:
        # Do not default. Mark incomplete so downstream cost aggregation excludes it.
        span.set_attribute("gen_ai.telemetry.incomplete", True)
        span.end()
        return

    span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
    span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    span.set_attribute("gen_ai.response.finish_reasons", finish_reasons)

    required = REQUIRED_BY_OPERATION.get(span.operation_name, set())
    missing = required - set(span.attributes)
    if missing:
        raise GenAISpanAttributeLoss(
            f"ending {span.operation_name!r} span with missing attributes: {sorted(missing)}"
        )
    span.end()
