# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-trust-registry-s-jurisdiction-tag-disagrees-with-the-warrant-s-asserted-jurisdiction-at-handoff-time.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-trust-registry-s-jurisdiction-tag-disagrees-with-the-warrant-s-asserted-jurisdiction-at-handoff-time.warrant.json
# Markdown SHA-256:   378c0ec95d785873c0d1fb03d67fc281adb9ddfa64fdcec2dba3d7f8210404c4
# Code AST SHA-256:   23aff1822c24edccd31217bd8fdb316ad7a94e4d1c35c5a71393060932d8686d
# Verified Classes:   JurisdictionDivergenceError, DivergenceKind, Warrant, RegistryEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class JurisdictionDivergenceError(RuntimeError):
    """Raised when warrant-asserted and registry-tagged jurisdictions are
    valid but disjoint, or drawn from uncomparable vocabularies. Must be
    raised BEFORE the first tool call, never after."""


class DivergenceKind(Enum):
    DISJOINT = "disjoint"        # both valid, empty intersection -> halt
    UNCOMPARABLE = "uncomparable"  # different vocabularies -> escalate


# Same enumerated lattice; extend as federation grows. Values NOT in this
# set are uncomparable by construction, not merely unequal.
JURISDICTION_LATTICE = {"EU", "US", "UK", "CA"}


@dataclass(frozen=True)
class Warrant:
    subject: str
    jurisdiction: str
    issued_at: int
    signature_valid: bool


@dataclass(frozen=True)
class RegistryEntry:
    subject: str
    jurisdiction: str
    updated_at: int


def effective_jurisdiction(warrant: Warrant, entry: RegistryEntry) -> str:
    """Return the effective jurisdiction for a handoff, or raise.

    Preconditions enforced here, not by caller:
      - signature must be valid (necessary, insufficient)
      - registry entry must not supersede the warrant (drift -> re-issue)
      - both values must be in the same lattice (else uncomparable)
      - intersection must be non-empty (else disjoint -> halt)
    """
    if not warrant.signature_valid:
        raise JurisdictionDivergenceError(
            f"warrant for {warrant.subject!r} has invalid signature"
        )

    if entry.subject != warrant.subject:
        raise JurisdictionDivergenceError(
            f"registry entry subject {entry.subject!r} != warrant subject "
            f"{warrant.subject!r}; cannot compare jurisdictions"
        )

    # Registry superseded the warrant: expected drift, not a halt condition.
    # Caller must re-issue the warrant against the current entry.
    if entry.updated_at > warrant.issued_at:
        raise JurisdictionDivergenceError(
            f"registry entry for {warrant.subject!r} updated at "
            f"{entry.updated_at} > warrant issued_at {warrant.issued_at}; "
            f"re-issue warrant, do not route"
        )

    j_w, j_r = warrant.jurisdiction, entry.jurisdiction

    if j_w not in JURISDICTION_LATTICE or j_r not in JURISDICTION_LATTICE:
        raise JurisdictionDivergenceError(
            f"uncomparable jurisdictions for {warrant.subject!r}: "
            f"warrant={j_w!r} registry={j_r!r} (kind="
            f"{DivergenceKind.UNCOMPARABLE.value}); escalate to vocabulary "
            f"reconciliation, do not treat as disjoint"
        )

    if j_w == j_r:
        return j_w

    # Both valid, same lattice, unequal. In this lattice jurisdictions are
    # atomic (no subset relation modeled); unequal means empty intersection.
    # Halt. Do not fall back to either value.
    raise JurisdictionDivergenceError(
        f"empty jurisdiction intersection for {warrant.subject!r}: "
        f"warrant asserts {j_w!r}, registry tags {j_r!r} "
        f"(kind={DivergenceKind.DISJOINT.value}); halt before first tool call"
    )


def admit_handoff(warrant: Warrant, entry: RegistryEntry) -> str:
    """Pre-execution gate. Returns effective jurisdiction to stamp onto
    every downstream tool call. Raises before any call is made."""
    effective = effective_jurisdiction(warrant, entry)
    # Caller is contractually required to stamp `effective` onto every
    # tool-call context; using warrant.jurisdiction for residency decisions
    # is the silent-violation path.
    return effective
