# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-but-still-cached-peer-warrant-as-a-live-trust-anchor-during-cross-domain-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-but-still-cached-peer-warrant-as-a-live-trust-anchor-during-cross-domain-handoff.warrant.json
# Markdown SHA-256:   c0ee4bf8796070bfa0eaf66ad9380decc9207877bdb774f9862ba5cc3d1a9b87
# Code AST SHA-256:   e156fdd5a183310255222e9d056b70ecc5c0959fcf8a07b4e94ccfe5e557f240
# Verified Classes:   TrustStateUnknown, Warrant, Anchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TrustStateUnknown(RuntimeError):
    """Raised when a foreign warrant's trust state cannot be bounded locally."""
    pass


@dataclass(frozen=True)
class Warrant:
    id: str
    issuer: str
    exp: float          # absolute epoch seconds
    signature_ok: bool


@dataclass(frozen=True)
class Anchor:
    domain: str
    fetched_at: float
    rotation_budget: float   # max age before anchor must be re-verified
    freshness_witness_ok: bool


def admit_foreign_handoff(
    warrant: Warrant,
    anchor: Anchor,
    local_revocation_set: set[str],
    max_revocation_skew: float | None,   # None => issuer publishes no bound
    now: float | None = None,
    handoff_deadline: float | None = None,
) -> bool:
    now = time.time() if now is None else now

    # Provable distrust: hard reject.
    if warrant.id in local_revocation_set:
        return False
    if not warrant.signature_ok:
        return False
    if now >= warrant.exp:
        return False

    # Anchor must be provably fresh, not merely present.
    if not anchor.freshness_witness_ok:
        raise TrustStateUnknown(
            f"anchor for {anchor.domain} lacks freshness witness; "
            f"cannot bound staleness"
        )
    anchor_age = now - anchor.fetched_at
    if anchor_age > anchor.rotation_budget:
        # Provable distrust of the anchor itself.
        return False

    # Foreign revocation skew must be bounded; silence is not proof.
    if max_revocation_skew is None:
        raise TrustStateUnknown(
            f"issuer {warrant.issuer} publishes no revocation skew bound; "
            f"absence of revocation record is not evidence of non-revocation"
        )

    remaining = warrant.exp - now
    if handoff_deadline is not None:
        remaining = min(remaining, handoff_deadline - now)

    total_uncertainty = max_revocation_skew + anchor_age
    if total_uncertainty >= remaining:
        raise TrustStateUnknown(
            f"trust uncertainty {total_uncertainty:.2f}s exceeds remaining "
            f"lifetime {remaining:.2f}s for warrant {warrant.id} from "
            f"{warrant.issuer}; fail closed"
        )

    return True
