# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-parent-a-genai-span-when-a-mid-turn-tool-call-opens-a-new-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-parent-a-genai-span-when-a-mid-turn-tool-call-opens-a-new-trace-context.warrant.json
# Markdown SHA-256:   6e2fc66414e81d5c8024c0df88dc17ac4242766fa0cb746180cbce0933306d8f
# Code AST SHA-256:   6ddc034b4dc3423d07785ddfdf56ac4569e4e5313027611714a4072103387f65
# Verified Classes:   TraceAttributionError, SpanCtx
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class TraceAttributionError(RuntimeError):
    """Raised when a GenAI span would be parented across a trace boundary."""


@dataclass(frozen=True)
class SpanCtx:
    trace_id: str
    span_id: str
    is_remote: bool = False


def next_llm_span_parent(
    turn_root: SpanCtx,
    returned_ctx: SpanCtx | None,
    conversation_id: str,
) -> tuple[SpanCtx, list[SpanCtx]]:
    """
    Decide the parent for the next gen_ai.* LLM span in a multi-turn agent turn.

    Returns (parent_ctx, links). The parent is ALWAYS the retained turn root
    unless the returned context shares the turn root's trace_id, in which case
    the returned context is a legitimate in-trace parent.
    """
    if turn_root.trace_id != turn_root.trace_id:  # defensive, unreachable
        raise TraceAttributionError("turn root is self-inconsistent")

    if not conversation_id:
        raise TraceAttributionError(
            "gen_ai.conversation.id missing; cannot attribute multi-turn span"
        )

    if returned_ctx is None:
        # Transport stripped context: parent on turn root, no link.
        return turn_root, []

    if returned_ctx.trace_id == turn_root.trace_id:
        # Same trace: safe to parent on the returned (in-trace) span.
        return returned_ctx, []

    # Cross-trace: MUST NOT parent. Link instead, keep turn-root parentage.
    if returned_ctx.trace_id == turn_root.trace_id:
        raise TraceAttributionError("unreachable")

    # Explicit guard: refuse any caller that tries to bypass this function.
    if returned_ctx.is_remote and returned_ctx.trace_id != turn_root.trace_id:
        links = [returned_ctx]
        return turn_root, links

    raise TraceAttributionError(
        f"returned context trace_id={returned_ctx.trace_id!r} diverges from "
        f"turn root trace_id={turn_root.trace_id!r} for conversation "
        f"{conversation_id!r}; refusing cross-trace parentage"
    )


def assert_same_trace(spans: list[SpanCtx], turn_root: SpanCtx) -> None:
    """Post-condition: every span in a turn shares the turn root's trace_id."""
    for s in spans:
        if s.trace_id != turn_root.trace_id:
            raise TraceAttributionError(
                f"span {s.span_id} in trace {s.trace_id} escaped turn root "
                f"trace {turn_root.trace_id}; attribution invariant violated"
            )
