# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-litmus-safety-failure-spans-with-opentelemetry-genai-semantic-conventions-before-emitting-telemetry.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-litmus-safety-failure-spans-with-opentelemetry-genai-semantic-conventions-before-emitting-telemetry.warrant.json
# Markdown SHA-256:   653c318087c47e1bf07cecad65a2f7b9b757847b33e8b0eb9948e23935c316f9
# Code AST SHA-256:   643f386fbd8495f14d05bf57260e8918c46e01d912c4dbfdf334ca9cf56fe473
# Verified Classes:   TelemetryMappingError, SpanContext, GenAISpan, LitmusVerdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class TelemetryMappingError(RuntimeError):
    """Raised when a LITMUS verdict cannot be legally represented as GenAI telemetry."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str


@dataclass
class GenAISpan:
    context: SpanContext
    operation_name: str
    ended: bool = False

    def add_event(self, name: str, attrs: dict) -> None:
        # Mirrors the SDK's NonRecordingSpan no-op: silently drops on ended spans.
        if self.ended:
            return
        # ... recording path elided ...


@dataclass(frozen=True)
class LitmusVerdict:
    probe_id: str
    outcome: str  # "pass" | "fail"
    target: SpanContext
    score_latency_ms: float


def emit_verdict(
    verdict: LitmusVerdict,
    target_span: GenAISpan,
    flush_horizon_ms: float,
    allow_custom_namespace: bool,
) -> GenAISpan:
    # Invariant 1: span-liveness at assignment time.
    if not target_span.ended and verdict.score_latency_ms <= flush_horizon_ms:
        target_span.add_event(
            "litmus.verdict",
            {"litmus.probe_id": verdict.probe_id, "litmus.outcome": verdict.outcome},
        )
        return target_span

    # Attach strategy is invalid past the flush horizon; must link a new span.
    if target_span.ended and verdict.score_latency_ms > flush_horizon_ms:
        if not allow_custom_namespace:
            # Invariant 2: without a declared custom namespace the collector
            # will drop litmus.* attributes under strict GenAI validation.
            raise TelemetryMappingError(
                f"verdict {verdict.probe_id}: target span {target_span.context.span_id} "
                f"already ended (latency {verdict.score_latency_ms}ms > flush "
                f"{flush_horizon_ms}ms) and custom namespace is disabled; "
                f"emitting would silently drop the failure"
            )
        linked = GenAISpan(
            context=SpanContext(trace_id=target_span.context.trace_id, span_id="scorer-" + verdict.probe_id),
            operation_name="litmus.score",
        )
        linked.add_event(
            "litmus.verdict",
            {
                "litmus.probe_id": verdict.probe_id,
                "litmus.outcome": verdict.outcome,
                "litmus.linked_span_id": target_span.context.span_id,
            },
        )
        return linked

    # Ended but latency within horizon: inconsistent state, refuse rather than guess.
    raise TelemetryMappingError(
        f"verdict {verdict.probe_id}: ended span with sub-horizon latency "
        f"({verdict.score_latency_ms}ms) indicates flush/score ordering bug"
    )


def self_test(flush_horizon_ms: float = 500.0) -> None:
    span = GenAISpan(SpanContext("t1", "s1"), operation_name="gen_ai.chat")
    span.ended = True
    fail = LitmusVerdict("probe-7", "fail", span.context, score_latency_ms=900.0)
    # Guardrail: if the fail-direction probe cannot be represented, abort.
    try:
        emit_verdict(fail, span, flush_horizon_ms, allow_custom_namespace=False)
    except TelemetryMappingError:
        raise TelemetryMappingError(
            "fail-direction verdict unrepresentable at startup; refusing to emit "
            "benchmark telemetry that would under-report safety failures"
        )
