# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-span-whose-genai-semantic-convention-attributes-were-mutated-mid-lifecycle-by-a-second-tracer-and-how-does.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-span-whose-genai-semantic-convention-attributes-were-mutated-mid-lifecycle-by-a-second-tracer-and-how-does.warrant.json
# Markdown SHA-256:   e1626e5932648ad5d24b85a8364eb944e873734465a97d2cac146329da7a5841
# Code AST SHA-256:   97c26726a5ef1ab96a1772e056051dc394d066df8e0038f36e2b91de9843d632
# Verified Classes:   GenAISpanConformanceError, SpanRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class GenAISpanConformanceError(RuntimeError):
    """Raised when a span's gen_ai.* attribute set violates the joint
    single-writer / status-coupling / post-end-immutability invariant."""


REQUIRED_KEYS = {"gen_ai.operation.name", "gen_ai.request.model"}
CONDITIONAL_KEYS = {
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.response.finish_reasons",
}
STATUS_COUPLED_KEYS = {"gen_ai.usage.input_tokens", "gen_ai.response.finish_reasons"}


@dataclass
class SpanRecord:
    attributes: dict[str, Any]
    writer_by_key: dict[str, str]
    status_code: str  # "UNSET" | "OK" | "ERROR"
    status_transitions: int
    ended: bool
    end_ns: int
    prompt_nonempty: bool
    write_ts_ns: dict[str, int] = field(default_factory=dict)


def validate_genai_span(span: SpanRecord, initializing_layer: str) -> None:
    # 1. single-writer invariant on required + conditional keys
    for key in REQUIRED_KEYS | CONDITIONAL_KEYS:
        if key in span.attributes:
            writer = span.writer_by_key.get(key)
            if writer is None:
                raise GenAISpanConformanceError(
                    f"key {key!r} present with no recorded writer"
                )
            if writer != initializing_layer:
                raise GenAISpanConformanceError(
                    f"key {key!r} written by {writer!r}, "
                    f"not initializing layer {initializing_layer!r}"
                )

    # 2. status-attribute coupling
    if span.status_transitions > 1:
        raise GenAISpanConformanceError(
            f"status.code transitioned {span.status_transitions} times; "
            "status must be set once"
        )
    if (
        span.status_code == "UNSET"
        and span.prompt_nonempty
        and span.attributes.get("gen_ai.usage.input_tokens") == 0
    ):
        raise GenAISpanConformanceError(
            "input_tokens==0 on UNSET span with non-empty prompt "
            "(status/usage coupling violated)"
        )
    if span.status_code == "ERROR" and "gen_ai.response.finish_reasons" in span.attributes:
        raise GenAISpanConformanceError(
            "finish_reasons present on ERROR span (response body presupposed)"
        )

    # 3. post-end immutability
    if span.ended:
        for key, ts in span.write_ts_ns.items():
            if ts > span.end_ns:
                raise GenAISpanConformanceError(
                    f"key {key!r} written at {ts} after end at {span.end_ns}"
                )


def reconcile_aggregate(
    parent: SpanRecord, children: list[SpanRecord], sampled_children: int
) -> None:
    if sampled_children != len(children):
        # aggregate unverifiable; must be annotated, not silently trusted
        return
    child_in = sum(c.attributes.get("gen_ai.usage.input_tokens", 0) for c in children)
    parent_in = parent.attributes.get("gen_ai.usage.input_tokens", 0)
    if child_in != parent_in:
        raise GenAISpanConformanceError(
            f"aggregate mismatch: parent input_tokens={parent_in}, "
            f"sum(children)={child_in}"
        )
