# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-span-because-required-semantic-convention-attributes-are-absent-at-span-close-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-span-because-required-semantic-convention-attributes-are-absent-at-span-close-time.warrant.json
# Markdown SHA-256:   f0019d9df30788a6868398397a07d2ea6a4dd0f5899adfe0d884b1cdfa4922c6
# Code AST SHA-256:   ebbc03c723194ddf5e2f269341147f40eb75ccd862693786939197257ee39378
# Verified Classes:   SpanContractViolation, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

REQUIRED_IDENTITY = ("gen_ai.operation.name", "gen_ai.request.model")
REQUIRED_ACCOUNTING = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
TERMINAL = ("gen_ai.response.finish_reasons",)


class SpanContractViolation(RuntimeError):
    """Raised when a GenAI span would close in a state the convention forbids."""


@dataclass
class GenAISpan:
    name: str
    attributes: dict = field(default_factory=dict)
    status: str = "UNSET"
    error_type: Optional[str] = None
    ended: bool = False

    def set_attribute(self, key: str, value) -> None:
        if self.ended:
            raise SpanContractViolation(f"attribute {key} set after span.end()")
        self.attributes[key] = value

    def set_status(self, status: str, description: str = "") -> None:
        self.status = status
        if description:
            self.attributes["otel.status_description"] = description


def close_genai_span(span: GenAISpan, *, operation_outcome: str) -> None:
    """Validate required-attribute contract at close time, then end the span.

    operation_outcome in {"success", "error", "cancel", "timeout"}.
    """
    if span.ended:
        raise SpanContractViolation(f"double-close on span {span.name}")

    attrs = span.attributes

    # Identity attributes are hard requirements: an unattributable span corrupts lineage.
    missing_identity = [k for k in REQUIRED_IDENTITY if k not in attrs]
    if missing_identity:
        span.set_status("ERROR", f"missing identity attrs: {missing_identity}")
        span.error_type = "span_contract_violation"
        span.ended = True
        raise SpanContractViolation(
            f"span {span.name} missing identity attributes {missing_identity}; "
            "cannot attribute to a model, refusing to emit"
        )

    # Partial accounting with no terminal reason is the silent-leak state.
    has_usage = any(k in attrs for k in REQUIRED_ACCOUNTING)
    has_terminal = any(k in attrs for k in TERMINAL)
    if has_usage and not has_terminal:
        # Strip partial usage so downstream treats it as unknown, not zero.
        for k in REQUIRED_ACCOUNTING:
            attrs.pop(k, None)
        span.set_status("ERROR", "partial usage without finish_reasons")
        span.error_type = "missing_terminal_accounting"
        span.ended = True
        raise SpanContractViolation(
            f"span {span.name} carried partial usage without finish_reasons "
            f"(outcome={operation_outcome}); stripped usage and flagged as error"
        )

    # Non-success outcomes with no accounting at all are emit-and-flag.
    if operation_outcome != "success" and not has_usage:
        span.set_status("ERROR", f"no accounting on outcome={operation_outcome}")
        span.error_type = span.error_type or f"unaccounted_{operation_outcome}"

    span.ended = True
