# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-trace-a-semantic-convention-span-link-when-a-parent-agent-hands-off-to-a-sub-agent-tree-and-the-otel-parent-span-id-crosses-a-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-trace-a-semantic-convention-span-link-when-a-parent-agent-hands-off-to-a-sub-agent-tree-and-the-otel-parent-span-id-crosses-a-t.warrant.json
# Markdown SHA-256:   5625fe4eaa862e1bdcbd7d57fa9e7921b61dce477308fecbbbca1cfe6512f114
# Code AST SHA-256:   217d285eb24017229e3e37abba3a30a7206431dee5c2d6cdb67b3c194a304b60
# Verified Classes:   SpanContext, CrossTraceParentPointerError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    agent_id: str


class CrossTraceParentPointerError(RuntimeError):
    """Raised when a sub-agent span sets parent_span_id across a trace boundary."""


def emit_subagent_root_span(
    child_ctx: SpanContext,
    handed_ancestors: list[SpanContext],
) -> dict:
    """
    Build the root span payload for a sub-agent executing under its own trace_id.

    Invariant: parent_span_id may only be set when the parent shares the child's
    trace_id. Otherwise the causal edge MUST be expressed as SpanLink records
    covering the full ancestor chain.
    """
    if not handed_ancestors:
        # No causal predecessor handed off: legitimate standalone root.
        return {
            "trace_id": child_ctx.trace_id,
            "span_id": child_ctx.span_id,
            "parent_span_id": None,
            "links": [],
        }

    immediate = handed_ancestors[-1]
    same_trace = immediate.trace_id == child_ctx.trace_id

    if same_trace:
        if len(handed_ancestors) > 1:
            # Ancestors beyond the immediate parent are still reachable by
            # walking parent_span_id within the shared trace; no links needed.
            pass
        return {
            "trace_id": child_ctx.trace_id,
            "span_id": child_ctx.span_id,
            "parent_span_id": immediate.span_id,
            "links": [],
        }

    # Cross-trace handoff: parent_span_id would be a dangling pointer.
    # Refuse to emit it; require links for the full ancestor chain instead.
    for anc in handed_ancestors:
        if anc.trace_id == child_ctx.trace_id:
            raise CrossTraceParentPointerError(
                f"ancestor {anc.agent_id}/{anc.span_id} shares child trace "
                f"{child_ctx.trace_id}; mixed-trace ancestor chain is "
                f"ambiguous — split the handoff payload."
            )

    links = [
        {
            "linked_trace_id": anc.trace_id,
            "linked_span_id": anc.span_id,
            "attributes": {
                "gen_ai.agent.handoff.source_agent_id": anc.agent_id,
                "gen_ai.agent.handoff.target_agent_id": child_ctx.agent_id,
                "gen_ai.agent.handoff.link_kind": "causal_ancestor",
            },
        }
        for anc in handed_ancestors
    ]

    return {
        "trace_id": child_ctx.trace_id,
        "span_id": child_ctx.span_id,
        "parent_span_id": None,  # suppressed: cross-trace
        "links": links,
    }
