# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-child-span-when-an-inbound-mcp-call-carries-an-unverifiable-traceparent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-child-span-when-an-inbound-mcp-call-carries-an-unverifiable-traceparent.warrant.json
# Markdown SHA-256:   41b04beb69fbdfb29f97c433dbdab0f15ef6e98db99bd750a8b14d20b076c8cc
# Code AST SHA-256:   41299d5006d05a5609fcd80e0f58c43624ce1015d6c9900b97635f39b98b840f
# Verified Classes:   TraceBindingMismatch, SpanIdCollision, InboundContext, SpanDecision, TraceAdopter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass

_TRACEPARENT_RE = re.compile(r"^([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})-([0-9a-f]{2})$")
_ZERO_TRACE = "0" * 32
_ZERO_SPAN = "0" * 16


class TraceBindingMismatch(RuntimeError):
    """Raised when an inbound traceparent cannot be verified against the caller's warrant."""


class SpanIdCollision(RuntimeError):
    """Raised when an inbound parent span-id was already observed as a parent in this trace."""


@dataclass(frozen=True)
class InboundContext:
    traceparent: str
    caller_warrant_digest: str | None  # None => unbound (no signed binding present)
    bound_warrant_digest: str | None   # digest bound into the trace context, if any


@dataclass(frozen=True)
class SpanDecision:
    adopt_parent: bool
    parent_span_id: str | None
    link_to: str | None
    reason: str


class TraceAdopter:
    def __init__(self) -> None:
        # per-trace set of parent span-ids already observed by this instance
        self._seen_parents: dict[str, set[str]] = {}

    def decide(self, ctx: InboundContext, new_span_id: str) -> SpanDecision:
        m = _TRACEPARENT_RE.match(ctx.traceparent)
        if not m:
            return SpanDecision(False, None, None, "malformed")
        trace_id, parent_span_id, _flags, _ver = m.groups()
        if trace_id == _ZERO_TRACE or parent_span_id == _ZERO_SPAN:
            return SpanDecision(False, None, None, "zero_sentinel")

        if ctx.caller_warrant_digest is None:
            raise TraceBindingMismatch(
                f"no verified caller warrant for trace {trace_id}; "
                "cannot adopt unbound parent"
            )

        if ctx.bound_warrant_digest is None:
            # syntactically valid but unbound: correlate via link, do not adopt
            return SpanDecision(False, None, ctx.traceparent, "unbound")

        if ctx.bound_warrant_digest != ctx.caller_warrant_digest:
            raise TraceBindingMismatch(
                f"trace {trace_id} bound to warrant {ctx.bound_warrant_digest!r} "
                f"but caller presented {ctx.caller_warrant_digest!r}"
            )

        seen = self._seen_parents.setdefault(trace_id, set())
        if parent_span_id in seen:
            # retry: model as sibling attempt, not second child of same parent
            return SpanDecision(False, None, ctx.traceparent, "retry_sibling")
        seen.add(parent_span_id)

        if new_span_id == parent_span_id:
            raise SpanIdCollision(
                f"new span-id {new_span_id} collides with inbound parent in trace {trace_id}"
            )
        return SpanDecision(True, parent_span_id, None, "adopted")
