# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-jurisdictional-residency-violation-that-occurs-only-after-a-capability-handoff-has-already-been-cryptographically-acce.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-jurisdictional-residency-violation-that-occurs-only-after-a-capability-handoff-has-already-been-cryptographically-acce.warrant.json
# Markdown SHA-256:   b1de2cc5fc77e5c8a6a923b1205c3a8c3071c12de8e2868fdb89fda7d8111460
# Code AST SHA-256:   c3e0e5b15a6c5a34df428af055389e903b150b9246e2704426ecf1ea1791f6ef
# Verified Classes:   ResidencyWarrantError, CapabilityGrant, LocusWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ResidencyWarrantError(RuntimeError):
    """Raised when a capability grant is used to authorize data movement
    without a fresh, region-matching execution-time locus attestation."""


@dataclass(frozen=True)
class CapabilityGrant:
    capability: str
    policy_region: str          # region the envelope claims
    expires_at: float


@dataclass(frozen=True)
class LocusWarrant:
    execution_region: str       # where the tool ACTUALLY ran
    issued_at: float
    ttl_seconds: float

    def is_fresh(self, now: float) -> bool:
        return (now - self.issued_at) <= self.ttl_seconds


def authorize_data_handoff(
    grant: CapabilityGrant,
    warrant: LocusWarrant | None,
    now: float,
    max_warrant_age_seconds: float = 30.0,
) -> None:
    # Capability validity is necessary but NOT sufficient for data movement.
    if now > grant.expires_at:
        raise ResidencyWarrantError(
            f"capability grant '{grant.capability}' expired at {grant.expires_at}"
        )

    # Missing warrant: the executing instance never attested its locus.
    # Deny-by-default — an un-attested hop is 'jurisdiction: unknown'.
    if warrant is None:
        raise ResidencyWarrantError(
            f"no locus warrant for capability '{grant.capability}'; "
            f"execution region unknown, cannot authorize data transfer"
        )

    # Stale warrant: locus may have changed since attestation (failover,
    # replica routing, cache fill). Reject rather than trust.
    if not warrant.is_fresh(now) or (now - warrant.issued_at) > max_warrant_age_seconds:
        raise ResidencyWarrantError(
            f"locus warrant age {now - warrant.issued_at:.1f}s exceeds "
            f"max {max_warrant_age_seconds}s for capability '{grant.capability}'"
        )

    # Region mismatch: the grant's envelope and the actual execution locus
    # disagree. This is the drift case — valid signature, wrong country.
    if warrant.execution_region != grant.policy_region:
        raise ResidencyWarrantError(
            f"residency drift: grant '{grant.capability}' envelope region "
            f"'{grant.policy_region}' != execution locus "
            f"'{warrant.execution_region}'"
        )
