# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-child-span-when-its-parent-trace-context-has-already-been-sampled-out-by-the-collector.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-child-span-when-its-parent-trace-context-has-already-been-sampled-out-by-the-collector.warrant.json
# Markdown SHA-256:   909d6206626763cd499fdb7a4a7ace06b5ec5dd87be7e66b365c128704f9627b
# Code AST SHA-256:   dcc9c37feb102371d96a4c76aa68d7817b0d32e26edccea9929caabc16ef8ab0
# Verified Classes:   GenAISpanEmissionError, SpanContextRef
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class GenAISpanEmissionError(RuntimeError):
    """Raised when a GenAI span would be emitted in a semantically undefined position."""


@dataclass(frozen=True)
class SpanContextRef:
    trace_id: str
    span_id: str
    sampled: bool
    is_remote: bool


def decide_genai_span_emission(
    parent: Optional[SpanContextRef],
    loop_root: Optional[SpanContextRef],
    operation_name: str,
) -> str:
    """
    Returns one of: 'emit', 'emit_with_link', 'suppress'.
    Raises GenAISpanEmissionError if the runtime cannot make a sound decision.
    """
    if not operation_name.startswith("gen_ai."):
        raise GenAISpanEmissionError(
            f"non-GenAI operation routed through GenAI emission gate: {operation_name!r}"
        )

    # No parent at all: only sound if we are genuinely at a root invocation.
    if parent is None:
        if loop_root is not None:
            # We are inside a loop but the parent context was lost (transport hop,
            # provider reset, or checkpoint resume). This is the re-rooting failure.
            return "emit_with_link"
        return "emit"

    if parent.sampled:
        return "emit"

    # Parent exists but was sampled out.
    if loop_root is not None and loop_root.sampled:
        return "emit_with_link"

    # Parent sampled out and no sampled ancestor resolvable in the loop.
    # Emitting here would create an orphan with no causal anchor.
    if loop_root is None and not parent.is_remote:
        raise GenAISpanEmissionError(
            f"parent {parent.span_id} sampled out and loop root evicted; "
            f"cannot emit {operation_name} without false-rooting the trace"
        )

    return "suppress"


def emit_genai_span(
    parent: Optional[SpanContextRef],
    loop_root: Optional[SpanContextRef],
    operation_name: str,
    attributes: dict,
) -> dict:
    decision = decide_genai_span_emission(parent, loop_root, operation_name)

    if decision == "suppress":
        # Do not emit a span; contribute to the metric counter instead.
        return {"emitted": False, "metric": "gen_ai.suppressed_span.count", "attrs": attributes}

    if decision == "emit_with_link":
        if loop_root is None:
            raise GenAISpanEmissionError(
                f"emit_with_link requested for {operation_name} but loop_root is None"
            )
        attributes = {**attributes, "gen_ai.parent_sampled": False, "gen_ai.trace_reparented": True}
        return {"emitted": True, "link_to": loop_root.span_id, "attrs": attributes}

    return {"emitted": True, "link_to": None, "attrs": attributes}
