# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-data-residency-policy-across-a-federation-boundary-and-the-peer-s-constraint-set-is-only-partially-disclosed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-data-residency-policy-across-a-federation-boundary-and-the-peer-s-constraint-set-is-only-partially-disclosed.warrant.json
# Markdown SHA-256:   336c290c6c2f5deacdc03297c9c20b8018baea3a656c670d42249802e2439c4b
# Code AST SHA-256:   5cfe5472c331fcdc0247eae1cb8836d9e0dea01caade0a15b23f2fc4ebac8dd4
# Verified Classes:   ResidencyNegotiationError, PolicyEnvelope, ClassBinding, Warrant
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ResidencyNegotiationError(RuntimeError):
    """Raised when a cross-federation residency handoff cannot be soundly authorized."""
    pass


@dataclass
class PolicyEnvelope:
    # Lossy projection: flat union of residencies across all classes.
    residencies: list[str]
    retention_days: int
    sub_processors: bool


@dataclass
class ClassBinding:
    data_class: str
    allowed_residencies: list[str]
    binding: bool  # True only if this is the peer's binding per-class clause.


@dataclass
class Warrant:
    payload_class: str
    target_federation: str
    binding: bool
    transcript_hash: str
    residency_ok: bool = False


def negotiate_and_dispatch(
    payload_class: str,
    required_jurisdiction: str,
    target_federation: str,
    envelope: PolicyEnvelope,
    class_binding: Optional[ClassBinding],
) -> Warrant:
    if not payload_class:
        raise ResidencyNegotiationError(
            "payload_class unknown; cannot negotiate residency at envelope granularity"
        )

    # Step 1: envelope match is discovery only, never authorization.
    if required_jurisdiction not in envelope.residencies:
        raise ResidencyNegotiationError(
            f"envelope for {target_federation} omits {required_jurisdiction}; "
            "fail closed before class-scoped negotiation"
        )

    # Step 2: require class-scoped binding response.
    if class_binding is None or class_binding.data_class != payload_class:
        raise ResidencyNegotiationError(
            f"no class-scoped binding for {payload_class} at {target_federation}; "
            "envelope match is insufficient and must not authorize dispatch"
        )

    if not class_binding.binding:
        raise ResidencyNegotiationError(
            f"peer returned advisory (binding=false) clause for {payload_class}; "
            "advisory clauses cannot carry a residency_ok warrant"
        )

    if required_jurisdiction not in class_binding.allowed_residencies:
        raise ResidencyNegotiationError(
            f"binding clause for {payload_class} at {target_federation} "
            f"excludes {required_jurisdiction}; envelope superset masked the exclusion"
        )

    transcript = f"{target_federation}:{payload_class}:{class_binding.allowed_residencies}"
    return Warrant(
        payload_class=payload_class,
        target_federation=target_federation,
        binding=True,
        transcript_hash=hashlib.sha256(transcript.encode()).hexdigest(),
        residency_ok=True,
    )


def audit_replay(warrant: Warrant, peer_class_binding: ClassBinding) -> None:
    """Auditor re-derives residency from the peer's per-class matrix, not the warrant bit."""
    if not warrant.binding:
        raise ResidencyNegotiationError("warrant lacks binding flag; replay unsafe")
    if peer_class_binding.data_class != warrant.payload_class:
        raise ResidencyNegotiationError("replay class mismatch")
    if not peer_class_binding.binding:
        raise ResidencyNegotiationError(
            "replay found advisory clause where binding was asserted; warrant poisoned"
        )
    # Recompute transcript hash to detect envelope-vs-class projection loss.
    expected = hashlib.sha256(
        f"{warrant.target_federation}:{warrant.payload_class}:"
        f"{peer_class_binding.allowed_residencies}".encode()
    ).hexdigest()
    if expected != warrant.transcript_hash:
        raise ResidencyNegotiationError(
            "transcript hash mismatch: warrant was issued against a different "
            "constraint set than the peer's binding clause"
        )
