# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-spans-whose-parent-context-was-exported-before-a-tool-call-re-entry-and-how-does-span-co.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-spans-whose-parent-context-was-exported-before-a-tool-call-re-entry-and-how-does-span-co.warrant.json
# Markdown SHA-256:   ee179aff137445ffd91fe0858aaaff26faf6a109d9f282ff61f39fb1bb876aaf
# Code AST SHA-256:   d03db4ebc51a64803858a238b0448fd1ca22e71a6245baced46c9cd138fa8010
# Verified Classes:   StaleSpanContextError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleSpanContextError(RuntimeError):
    """Raised when a checkpointed SpanContext is about to be used as a live parent."""
    pass


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    trace_flags: int
    # Lifecycle is NOT part of the wire context; it must be tracked separately
    # or presumed dead after serialization.
    serialized: bool = False
    ended: bool = True


def resolve_resume_parent(ctx: Optional[SpanContext]) -> str:
    """
    Decide how a resumed agent turn attaches to its captured context.
    Returns a mode: 'REATTACH' (live parent) or 'REROOT_LINK' (dead parent).
    Raises StaleSpanContextError if the context's liveness is unknowable.
    """
    if ctx is None:
        return "REROOT_LINK"  # no context at all -> fresh root

    if ctx.serialized and not ctx.ended:
        # Contradiction: a serialized context cannot prove liveness.
        raise StaleSpanContextError(
            f"context {ctx.trace_id}/{ctx.span_id} was serialized but claims "
            f"not-ended; liveness is unknowable across a process boundary"
        )

    if ctx.serialized or ctx.ended:
        # Presumptively dead: re-root and link, never re-attach.
        return "REROOT_LINK"

    # Live, in-memory, non-serialized handle: legal to re-attach.
    return "REATTACH"


def emit_resumed_chat_span(ctx: Optional[SpanContext], name: str) -> str:
    mode = resolve_resume_parent(ctx)
    if mode == "REATTACH":
        return f"span(parent={ctx.span_id}, name={name})"
    if mode == "REROOT_LINK":
        link = f"link({ctx.trace_id}/{ctx.span_id})" if ctx else "no-link"
        return f"span(root, name={name}, {link})"
    # Unreachable, but keeps the invariant explicit.
    raise StaleSpanContextError(f"unhandled resume mode {mode!r}")
