# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-link-a-child-span-to-a-parent-trace-when-an-a2a-task-id-crosses-an-mcp-transport-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-link-a-child-span-to-a-parent-trace-when-an-a2a-task-id-crosses-an-mcp-transport-hop.warrant.json
# Markdown SHA-256:   5f8f225ee929a35a12ff01f0b782ce8e55e28d1accfced583d0d09c78b275f34
# Code AST SHA-256:   6c6717c59b017f109b1887b9fc2315bbb7765c69d672a1a6d035c05153acfe49
# Verified Classes:   ContextSource, SpanForgeryError, SpanContext, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class ContextSource(Enum):
    TRACEPARENT = "traceparent"
    MCP_META = "mcp_meta"
    SIGNED_CARRIER = "signed_carrier"
    TASK_ID_INFERENCE = "task_id_inference"


class SpanForgeryError(RuntimeError):
    """Raised when a linker attempts to assert causal parentage from a domain identifier."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    source: ContextSource
    task_id: str | None = None


@dataclass(frozen=True)
class Span:
    context: SpanContext
    name: str


def link_child_to_parent(child: Span, parent: Span) -> Span:
    """Return child with parent edge asserted, or refuse.

    Refuses when the only evidence of parentage is a matching A2A Task.id.
    A matching task ID is a correlation key, not a causal key.
    """
    ctx = child.context

    if ctx.source is ContextSource.TASK_ID_INFERENCE:
        raise SpanForgeryError(
            f"refusing to link span {child.name!r} to {parent.name!r}: "
            f"parentage inferred solely from task_id={ctx.task_id!r}; "
            f"emit an OTel Link(correlation=task_id) instead of a parent edge"
        )

    if ctx.trace_id != parent.context.trace_id:
        raise SpanForgeryError(
            f"trace_id mismatch: child={ctx.trace_id} parent={parent.context.trace_id}"
        )

    if ctx.parent_span_id != parent.context.span_id:
        raise SpanForgeryError(
            f"parent_span_id mismatch: child names {ctx.parent_span_id}, "
            f"parent is {parent.context.span_id}"
        )

    # Legitimate: context was propagated in-band and names this parent.
    return child


def propagate_across_a2a(caller: Span, a2a_headers: dict[str, str]) -> SpanContext:
    """Model the A2A hop. If the transport dropped traceparent, the peer must
    start a fresh root and record task_id as correlation only."""
    tp = a2a_headers.get("traceparent")
    task_id = a2a_headers.get("x-a2a-task-id")
    if tp is None:
        # Honest fallback: new root, task_id is correlation, not causality.
        return SpanContext(
            trace_id="fresh-root-" + (task_id or "unknown"),
            span_id="peer-span-" + (task_id or "unknown"),
            parent_span_id=None,
            source=ContextSource.TASK_ID_INFERENCE,
            task_id=task_id,
        )
    parts = tp.split("-")
    return SpanContext(
        trace_id=parts[1],
        span_id="peer-span-" + (task_id or "unknown"),
        parent_span_id=parts[2],
        source=ContextSource.TRACEPARENT,
        task_id=task_id,
    )
