# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-spans-when-a-sub-agent-s-trace-context-is-severed-mid-call-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-spans-when-a-sub-agent-s-trace-context-is-severed-mid-call-graph.warrant.json
# Markdown SHA-256:   478c29446fdb0c1c925565c83dd147124917e49c550f53be4fbffece8a66eeaf
# Code AST SHA-256:   7eaadfa9b5bfa716ef5ef7f91dd2296db027ff76664b6bcd76175e5b9e939346
# Verified Classes:   OrphanedSpanError, SpanContext, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class OrphanedSpanError(RuntimeError):
    """Raised when a resumed sub-agent would emit a span with no resolvable parent."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str] = None
    replay: bool = False
    links: list = field(default_factory=list)


@dataclass
class Checkpoint:
    inbound_traceparent: Optional[str]   # serialized context of the invoking span
    outbound_span_id: Optional[str]     # span minted for the in-flight op, if any
    superseded_span_id: Optional[str]   # span of the attempt this resume replaces


def parse_traceparent(tp: Optional[str]) -> Optional[SpanContext]:
    if not tp:
        return None
    parts = tp.split("-")
    if len(parts) != 4:
        return None
    trace_id, span_id, _flags, _version = parts
    return SpanContext(trace_id=trace_id, span_id=span_id)


def resume_subagent_span(
    checkpoint: Checkpoint,
    decision: str,  # "adopt" | "fork"
) -> SpanContext:
    inbound = parse_traceparent(checkpoint.inbound_traceparent)

    if decision == "adopt":
        if inbound is None:
            raise OrphanedSpanError(
                "adopt requested but checkpoint carries no inbound traceparent; "
                "refusing to emit an orphan — fail closed instead."
            )
        # Continuation of the same logical operation: child of the inbound span.
        return SpanContext(
            trace_id=inbound.trace_id,
            span_id=uuid.uuid4().hex[:16],
            parent_span_id=inbound.span_id,
            replay=checkpoint.outbound_span_id is not None,
        )

    if decision == "fork":
        # New logical operation that supersedes the prior attempt: new root,
        # but a link (not a parent) records the dependency on the dead attempt.
        if checkpoint.superseded_span_id is None:
            raise OrphanedSpanError(
                "fork requested but no superseded span recorded; "
                "cannot distinguish a legitimate new root from a lost parent."
            )
        return SpanContext(
            trace_id=uuid.uuid4().hex,
            span_id=uuid.uuid4().hex[:16],
            parent_span_id=None,
            links=[checkpoint.superseded_span_id],
        )

    raise OrphanedSpanError(
        f"unknown resume decision {decision!r}; must be 'adopt' or 'fork'."
    )
