# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-traceparent-during-an-mcp-handoff-silent-trace-graph-fragmentation-across-federated-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-traceparent-during-an-mcp-handoff-silent-trace-graph-fragmentation-across-federated-agents.warrant.json
# Markdown SHA-256:   9ce83655f393429d52a4b206cfd722744dc4f0f39485f3b39e9a9e125beff375
# Code AST SHA-256:   f903e705fa852f148acf04bb7798c7a83a1ad6caa1e2d22ff68690016cddcfec
# Verified Classes:   TraceFragmentationError, InboundContext, EmittedSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

_TRACEPARENT = re.compile(
    r"^(?P<ver>[0-9a-f]{2})-(?P<trace>[0-9a-f]{32})-(?P<span>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)


class TraceFragmentationError(RuntimeError):
    """Raised when an emitted span severs the inbound trace_id while retaining its parent link."""


@dataclass(frozen=True)
class InboundContext:
    trace_id: str
    parent_id: str
    sampled: bool


@dataclass(frozen=True)
class EmittedSpan:
    trace_id: str
    span_id: str
    parent_id: str | None


def parse_traceparent(header: str) -> InboundContext:
    m = _TRACEPARENT.match(header.strip().lower())
    if not m:
        raise TraceFragmentationError(f"malformed traceparent: {header!r}")
    if m["trace"] == "0" * 32 or m["span"] == "0" * 16:
        raise TraceFragmentationError("all-zero trace_id or span_id is invalid per W3C")
    return InboundContext(
        trace_id=m["trace"],
        parent_id=m["span"],
        sampled=bool(int(m["flags"], 16) & 0x01),
    )


def assert_trace_integrity(inbound: InboundContext, emitted: EmittedSpan) -> None:
    """
    Enforce: if trace_id changes, parent_id MUST be None (declared boundary reset).
    If parent_id is set, trace_id MUST equal the inbound trace_id.
    Reset-while-retaining-parent is a hard error.
    """
    if emitted.parent_id is not None:
        if emitted.trace_id != inbound.trace_id:
            raise TraceFragmentationError(
                "trace fragmentation: emitted span retains parent_id="
                f"{emitted.parent_id!r} but mints new trace_id {emitted.trace_id!r} "
                f"(inbound trace_id was {inbound.trace_id!r}). "
                "Either propagate the inbound trace_id or drop parent_id and "
                "record the inbound context as a span link."
            )
        if emitted.parent_id != inbound.parent_id:
            raise TraceFragmentationError(
                f"parent_id mismatch: emitted {emitted.parent_id!r}, "
                f"inbound {inbound.parent_id!r} within same trace"
            )
    else:
        # Declared boundary reset: trace loss is permitted only with explicit
        # boundary annotation, which the caller must have set out-of-band.
        if emitted.trace_id == inbound.trace_id:
            raise TraceFragmentationError(
                "reset without new trace_id: parent_id dropped but trace_id "
                "unchanged, producing an orphan span"
            )


def handle_tool_call(raw_traceparent: str, trace_root_policy: str | None) -> EmittedSpan:
    """
    trace_root_policy must be explicitly negotiated ('caller' or 'boundary').
    A None policy is a negotiation failure and must NOT default silently.
    """
    if trace_root_policy not in ("caller", "boundary"):
        raise TraceFragmentationError(
            f"trace_root_policy not negotiated (got {trace_root_policy!r}); "
            "refusing to guess — silent default causes fragmentation"
        )
    inbound = parse_traceparent(raw_traceparent)

    if trace_root_policy == "caller":
        emitted = EmittedSpan(
            trace_id=inbound.trace_id,
            span_id="a1b2c3d4e5f60718",
            parent_id=inbound.parent_id,
        )
    else:  # boundary reset: new root, NO parent link
        emitted = EmittedSpan(
            trace_id="9f8e7d6c5b4a39281706f5e4d3c2b1a0",
            span_id="a1b2c3d4e5f60718",
            parent_id=None,
        )

    assert_trace_integrity(inbound, emitted)
    return emitted
