# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-trace-parent-when-an-mcp-tool-server-re-enters-an-a2a-sub-agent-the-trace-context-rebinding-gap-at-federated-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-trace-parent-when-an-mcp-tool-server-re-enters-an-a2a-sub-agent-the-trace-context-rebinding-gap-at-federated-boundaries.warrant.json
# Markdown SHA-256:   2ca2a75fbd3148b73425924f96d1718b8d1351ccbb5c08b8780fe2eabce0556b
# Code AST SHA-256:   d36524dcbc74e6ef969c266d9ae81185bb67d577f32c8aeacc9362de32c29aa5
# Verified Classes:   TraceRebindError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass

_TRACEPARENT = 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


class TraceRebindError(RuntimeError):
    """Raised when a federated hop would silently rebase a trace instead of continuing it."""


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


def extract_inbound(headers: dict[str, str]) -> SpanContext | None:
    raw = headers.get("traceparent")
    if raw is None:
        return None
    m = _TRACEPARENT.match(raw.strip())
    if not m or m["trace_id"] == _ZERO_TRACE:
        return None
    return SpanContext(
        trace_id=m["trace_id"],
        span_id=m["span_id"],
        sampled=bool(int(m["flags"], 16) & 0x01),
    )


def build_outbound(
    *,
    inbound: SpanContext | None,
    new_span_id: str,
    require_continuity: bool,
    caller_declared_trace: str | None,
) -> str:
    """Construct the outbound traceparent for an A2A dispatch from inside an MCP handler.

    The invariant: if continuity is required and an inbound context exists,
    the outbound trace_id MUST equal the inbound trace_id. A mismatch means
    the A2A client was built with a stale/empty context and we must refuse
    rather than emit a rebased trace that looks valid on the wire.
    """
    if inbound is None:
        if require_continuity:
            raise TraceRebindError(
                "continuity required but no inbound traceparent was extracted at "
                "handler entry; A2A client likely captured an empty boot-time context"
            )
        # Metadata-only hop: allowed, but caller must not assume a join exists.
        root = caller_declared_trace or "0" * 32
        return f"00-{root}-{new_span_id}-01"

    if caller_declared_trace is not None and caller_declared_trace != inbound.trace_id:
        raise TraceRebindError(
            f"outbound trace_id {caller_declared_trace} does not continue inbound "
            f"{inbound.trace_id}; refusing to emit a silently rebased trace"
        )

    flags = "01" if inbound.sampled else "00"
    return f"00-{inbound.trace_id}-{new_span_id}-{flags}"


def dispatch_research(
    *,
    request_headers: dict[str, str],
    a2a_client_trace: str | None,
    new_span_id: str,
    require_continuity: bool = True,
) -> str:
    inbound = extract_inbound(request_headers)
    return build_outbound(
        inbound=inbound,
        new_span_id=new_span_id,
        require_continuity=require_continuity,
        caller_declared_trace=a2a_client_trace,
    )
