# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-propagate-a-distributed-trace-context-across-a-federated-agent-mesh-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-propagate-a-distributed-trace-context-across-a-federated-agent-mesh-boundary.warrant.json
# Markdown SHA-256:   0de0776314bc02960ef21ffbe63b17057e15141df427cf900b138b3bd3f2ea8a
# Code AST SHA-256:   233c9a2f7b4491a8be05bf6dbc462aa7382ad861c984c7fd998c4bf4895c7035
# Verified Classes:   TracePropagationRefused, PropagationMode, InboundContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass
from enum import Enum

_TRACEPARENT = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")


class TracePropagationRefused(RuntimeError):
    """Raised when an inbound trace context must not be joined into the local causal graph."""


class PropagationMode(Enum):
    JOIN = "join"
    FORK = "fork"
    REFUSE = "refuse"


@dataclass(frozen=True)
class InboundContext:
    traceparent: str
    warrant_verified: bool          # signed claim binds trace-id to a recognized principal
    schema_compatible: bool         # receiver span schema is a refinement of origin's
    sampling_compatible: bool       # sampling decision satisfies receiver's audit obligation
    negotiated: bool                # schema negotiation completed (not a timeout fallback)


def classify(inbound: InboundContext) -> PropagationMode:
    m = _TRACEPARENT.match(inbound.traceparent)
    if not m:
        # Malformed context is not a refusal case; it is simply dropped upstream.
        raise TracePropagationRefused(
            f"unparseable traceparent={inbound.traceparent!r}; refuse to propagate"
        )
    trace_id, parent_id, flags = m.group(1), m.group(2), int(m.group(3), 16)
    if trace_id == "0" * 32 or parent_id == "0" * 16:
        raise TracePropagationRefused(
            f"all-zero trace/parent id in {inbound.traceparent!r}; forged or defaulted context"
        )
    if not inbound.warrant_verified:
        # No cryptographic binding: joining would let an attacker pre-seed the auditor replay.
        raise TracePropagationRefused(
            f"trace-id {trace_id} has no verified cross-mesh warrant; refuse to join"
        )
    if not (inbound.schema_compatible and inbound.sampling_compatible):
        # Valid provenance, incompatible semantics: fork, do not weld.
        return PropagationMode.FORK
    if not inbound.negotiated:
        # Timeout fallback must never upgrade to JOIN; fork preserves reference safely.
        return PropagationMode.FORK
    if not (flags & 0x01):
        # Origin sampled out but receiver requires sampling: forking avoids structural holes.
        return PropagationMode.FORK
    return PropagationMode.JOIN


def handle_handoff(inbound: InboundContext) -> dict[str, str]:
    mode = classify(inbound)
    if mode is PropagationMode.REFUSE:
        raise TracePropagationRefused("refuse mode reached without exception; invariant violated")
    if mode is PropagationMode.JOIN:
        return {"traceparent": inbound.traceparent, "mode": "join"}
    # FORK: mint a new trace, retain inbound trace-id as a link attribute only.
    m = _TRACEPARENT.match(inbound.traceparent)
    assert m is not None
    return {
        "traceparent": f"00-{_new_trace_id()}-{_new_span_id()}-01",
        "link.trace_id": m.group(1),
        "mode": "fork",
    }


def _new_trace_id() -> str:
    import secrets
    return secrets.token_hex(16)


def _new_span_id() -> str:
    import secrets
    return secrets.token_hex(8)
