# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-causal-parent-when-an-mcp-tool-call-crosses-an-a2a-hop-trace-context-divergence-at-the-delegation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-causal-parent-when-an-mcp-tool-call-crosses-an-a2a-hop-trace-context-divergence-at-the-delegation-boundary.warrant.json
# Markdown SHA-256:   78754fcd73de37859ad372f062a420a48a4161838115947d7e6ee60eafd9b7ba
# Code AST SHA-256:   efc4743a193b3f9c611e66378e9b42d9b7759174ae33176fbf3e66798a04d1c2
# Verified Classes:   TraceContextDivergenceError, SpanContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass

_TRACEPARENT_RE = re.compile(
    r"^(?P<version>[0-9a-f]{2})-"
    r"(?P<trace_id>[0-9a-f]{32})-"
    r"(?P<span_id>[0-9a-f]{16})-"
    r"(?P<flags>[0-9a-f]{2})$"
)
_ZERO_TRACE = "0" * 32
_ZERO_SPAN = "0" * 16


class TraceContextDivergenceError(RuntimeError):
    """Raised when a delegation edge would sever causal parentage.

    The receiving side would mint a fresh trace with no link to the
    caller's span, producing a divergent-but-plausible trace.
    """


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

    @property
    def valid(self) -> bool:
        return (
            self.trace_id != _ZERO_TRACE
            and self.span_id != _ZERO_SPAN
            and len(self.trace_id) == 32
            and len(self.span_id) == 16
        )


def parse_traceparent(header: str | None) -> SpanContext | None:
    if not header:
        return None
    m = _TRACEPARENT_RE.match(header.strip().lower())
    if not m:
        return None
    ctx = SpanContext(
        trace_id=m.group("trace_id"),
        span_id=m.group("span_id"),
        sampled=bool(int(m.group("flags"), 16) & 0x01),
    )
    return ctx if ctx.valid else None


def enforce_delegation_boundary(
    *,
    edge: str,                       # "mcp.tool.search_corpus" | "a2a.task.send"
    ambient: SpanContext | None,     # context attached in the *caller*
    inbound_header: str | None,      # traceparent as actually transmitted
    receiver_tracer_ready: bool,
    receiver_can_link: bool,
) -> SpanContext:
    """Assert causal parentage across a delegation edge.

    Called on the receiver before task acceptance. Returns the SpanContext
    the receiver must adopt as parent. Raises if adoption would diverge
    from the caller without an explicit link.
    """
    inbound = parse_traceparent(inbound_header)

    # Case 1: caller had no ambient context. This is a genuine root;
    # a new trace is legitimate, not divergence.
    if ambient is None:
        if inbound is not None:
            # Inbound claims a parent the caller never had -> spoofed or
            # replayed header. Refuse to trust it as causal.
            raise TraceContextDivergenceError(
                f"edge={edge}: inbound traceparent {inbound.trace_id} "
                f"present but caller had no ambient context (possible replay)"
            )
        return SpanContext(trace_id=_ZERO_TRACE, span_id=_ZERO_SPAN, sampled=False)

    if not ambient.valid:
        raise TraceContextDivergenceError(
            f"edge={edge}: caller ambient context is invalid "
            f"(trace={ambient.trace_id!r} span={ambient.span_id!r})"
        )

    # Case 2: caller had context but the header did not survive the transport.
    if inbound is None:
        if receiver_can_link:
            # Degraded but recorded: new trace, explicit link to ambient.
            return SpanContext(
                trace_id=_ZERO_TRACE, span_id=_ZERO_SPAN, sampled=ambient.sampled
            )
        raise TraceContextDivergenceError(
            f"edge={edge}: traceparent dropped in transit; caller trace "
            f"{ambient.trace_id} span {ambient.span_id} would be orphaned "
            f"and receiver cannot emit a link"
        )

    # Case 3: header present but disagrees with caller's ambient context.
    if inbound.trace_id != ambient.trace_id:
        raise TraceContextDivergenceError(
            f"edge={edge}: trace_id divergence "
            f"caller={ambient.trace_id} inbound={inbound.trace_id} "
            f"(retry re-derivation or header allowlist bug)"
        )

    # Case 4: cold-start receiver whose provider is not yet live.
    if not receiver_tracer_ready:
        raise TraceContextDivergenceError(
            f"edge={edge}: receiver accepted task before tracer provider "
            f"ready; span would be re-parented to synthetic root "
            f"(trace={inbound.trace_id})"
        )

    return inbound


def build_outbound_headers(
    *,
    edge: str,
    ambient: SpanContext | None,
    business_headers: dict[str, str],
) -> dict[str, str]:
    """Re-inject traceparent from *current* ambient context on every attempt.

    Retries must call this again with a freshly-read ambient context;
    never reuse a header dict snapshotted at first-attempt build time.
    """
    headers = dict(business_headers)
    if ambient is None:
        return headers
    if not ambient.valid:
        raise TraceContextDivergenceError(
            f"edge={edge}: refusing to emit invalid span context "
            f"(trace={ambient.trace_id!r})"
        )
    flags = "01" if ambient.sampled else "00"
    headers["traceparent"] = f"00-{ambient.trace_id}-{ambient.span_id}-{flags}"
    return headers
