# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-a-federated-trust-boundary-span-id-reuse-and-the-poisoned-correlation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-a-federated-trust-boundary-span-id-reuse-and-the-poisoned-correlation-invariant.warrant.json
# Markdown SHA-256:   5d4ac32eaffb67e4a80897a8a761d4647b7e825441a8993ee1e73c89983f7b11
# Code AST SHA-256:   cd0012076b7ecf3d66d1c9f882bf0a26b8197ea324e4914e4c54b0acd86c9c45
# Verified Classes:   UnverifiedTraceLineageError, SpanRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass, field


class UnverifiedTraceLineageError(RuntimeError):
    """Raised when an inbound traceparent cannot be bound to a trusted lineage."""


@dataclass
class SpanRegistry:
    # (trace_id, span_id) -> first_seen monotonic ts, per peer domain
    seen: dict = field(default_factory=dict)
    ttl_seconds: float = 3600.0

    def _prune(self, now: float) -> None:
        cutoff = now - self.ttl_seconds
        self.seen = {k: v for k, v in self.seen.items() if v >= cutoff}

    def check_and_record(self, peer: str, trace_id: str, span_id: str) -> bool:
        """Return True if this (trace_id, span_id) is novel; False on collision."""
        now = time.monotonic()
        self._prune(now)
        key = (peer, trace_id, span_id)
        if key in self.seen:
            return False
        # cross-trace span-ID reuse: same peer, same span_id, different trace_id
        for (p, t, s), _ in self.seen.items():
            if p == peer and s == span_id and t != trace_id:
                return False
        self.seen[key] = now
        return True


def verify_inbound_traceparent(
    peer: str,
    traceparent: str,
    tracestate: str,
    peer_hmac_key: bytes,
    registry: SpanRegistry,
    ancestor_chain_resolvable: bool,
    policy_depends_on_ancestors: bool,
) -> str:
    """
    Returns 'adopt' | 'reroot' | raises UnverifiedTraceLineageError.
    """
    parts = traceparent.split("-")
    if len(parts) != 4 or len(parts[1]) != 32 or len(parts[2]) != 16:
        raise UnverifiedTraceLineageError(f"malformed traceparent from {peer}: {traceparent!r}")
    _, trace_id, span_id, _flags = parts

    # 1. provenance binding: signed tracestate entry over (trace_id, span_id)
    expected = hmac.new(peer_hmac_key, f"{trace_id}:{span_id}".encode(), hashlib.sha256).hexdigest()
    sig = None
    for entry in tracestate.split(","):
        entry = entry.strip()
        if entry.startswith(f"{peer}@sig="):
            sig = entry.split("=", 1)[1]
            break
    provenance_bound = sig is not None and hmac.compare_digest(sig, expected)

    # 2. span-ID non-reuse
    novel = registry.check_and_record(peer, trace_id, span_id)

    # 3. ancestor visibility
    if policy_depends_on_ancestors and not ancestor_chain_resolvable:
        raise UnverifiedTraceLineageError(
            f"policy depends on ancestor attributes but chain for trace {trace_id} "
            f"from {peer} is not resolvable; refusing to proceed"
        )

    if provenance_bound and novel and ancestor_chain_resolvable:
        return "adopt"
    if not novel:
        # collision: never adopt; re-root under a fresh local trace
        return "reroot"
    if not provenance_bound:
        return "reroot"
    return "adopt"


def handle_remote_tool_call(
    peer: str,
    traceparent: str,
    tracestate: str,
    peer_hmac_key: bytes,
    registry: SpanRegistry,
    ancestor_chain_resolvable: bool,
    policy_depends_on_ancestors: bool,
) -> str:
    decision = verify_inbound_traceparent(
        peer, traceparent, tracestate, peer_hmac_key, registry,
        ancestor_chain_resolvable, policy_depends_on_ancestors,
    )
    if decision == "reroot":
        # caller mints a fresh trace; inbound traceparent is recorded as a Link
        # with link.unverified=true, never as Parent.
        return "rerooted"
    return "adopted"
