# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-span-parentage-when-a-tool-call-graph-is-re-entered-after-a-mid-trajectory-resume-and-why-the-genai-semantic-conventi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-span-parentage-when-a-tool-call-graph-is-re-entered-after-a-mid-trajectory-resume-and-why-the-genai-semantic-conventi.warrant.json
# Markdown SHA-256:   45747e94c3b66ced79b489707e4b3f43e777fba3437e92ca390b55261c20d16e
# Code AST SHA-256:   88a5b50bed17bb8676d57a07350ab1ed0792d580095ad2a740a580d485b61072
# Verified Classes:   TrajectoryForkError, Span, CheckpointBoundary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict


class TrajectoryForkError(RuntimeError):
    """Raised when a resumed trajectory produces a second causal root
    or a duplicate executed-tool span under one gen_ai.conversation.id."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    conversation_id: str
    operation: str
    tool_call_id: str | None = None
    status: str = "UNSET"


@dataclass
class CheckpointBoundary:
    trace_id: str
    open_span_id: str          # span open at checkpoint time = reattachment point
    completed_tool_call_ids: set[str] = field(default_factory=set)


def reattach_on_resume(
    checkpoint: CheckpointBoundary,
    new_root: Span,
    replayed_turns: list[Span],
) -> list[Span]:
    """Reattach a resumed trajectory to its pre-checkpoint span tree.

    Replayed turns must be converted to SpanLinks, not re-emitted as
    executed spans. Returns the spans safe to export.
    """
    if new_root.parent_span_id is not None:
        raise TrajectoryForkError(
            f"resumed root {new_root.span_id} already has a parent; "
            "reattachment must start from a root context"
        )

    # Reattach the resumed root to the span that was open at checkpoint.
    new_root.parent_span_id = checkpoint.open_span_id
    new_root.trace_id = checkpoint.trace_id  # inherit, do not fork trace

    exported: list[Span] = []
    for span in replayed_turns:
        if span.tool_call_id in checkpoint.completed_tool_call_ids:
            # Already executed before checkpoint: must NOT re-emit as executed.
            # Caller converts this to a SpanLink; we refuse to export it.
            continue
        exported.append(span)

    # Guard: single executed span per (conversation, tool_call_id).
    seen: dict[tuple[str, str], int] = defaultdict(int)
    for span in exported + [new_root]:
        if span.operation == "execute_tool" and span.tool_call_id:
            seen[(span.conversation_id, span.tool_call_id)] += 1
    for key, count in seen.items():
        if count > 1:
            raise TrajectoryForkError(
                f"tool_call_id {key[1]} executed {count}x under "
                f"conversation {key[0]}; replay was re-emitted as execution"
            )

    return exported + [new_root]
