# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-verifiable-credential-was-revoked-mid-handoff-before-the-peer-s-authorization-cache-expires.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-verifiable-credential-was-revoked-mid-handoff-before-the-peer-s-authorization-cache-expires.warrant.json
# Markdown SHA-256:   d4bda807361944d59ce2c0bc24d3db90ab4d11b51a05185032d15b81647f2b84
# Code AST SHA-256:   4dcc8166687962642d73496b30b7ac16c07ce78aa74486ea2ec0b8415605fa3c
# Verified Classes:   RevocationFreshnessError, StatusSnapshot, PeerAuthCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationFreshnessError(RuntimeError):
    """Raised when self-authorization cannot be proven current within peer cache bounds."""
    pass


@dataclass
class StatusSnapshot:
    revoked: bool
    last_sync: float  # epoch seconds of the replica's last authoritative sync


@dataclass
class PeerAuthCache:
    peer_id: str
    cache_ttl: float


def assert_self_authorized(
    snapshot: StatusSnapshot,
    peers: list[PeerAuthCache],
    max_replica_lag: float,
    self_check_interval: float,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now
    data_age = now - snapshot.last_sync

    if snapshot.revoked:
        raise RevocationFreshnessError(
            f"authoritative revocation observed (age={data_age:.1f}s); halt and ack peers"
        )

    if data_age > max_replica_lag:
        raise RevocationFreshnessError(
            f"self-check data stale: age={data_age:.1f}s > max_replica_lag={max_replica_lag:.1f}s; "
            "state is indeterminate, not authorized"
        )

    if not peers:
        return

    tightest_peer_ttl = min(p.cache_ttl for p in peers)
    safety_bound = max_replica_lag + self_check_interval
    if safety_bound >= tightest_peer_ttl:
        raise RevocationFreshnessError(
            f"safety inequality violated: max_replica_lag+interval={safety_bound:.1f}s "
            f">= tightest peer cache_ttl={tightest_peer_ttl:.1f}s; "
            "cannot guarantee we stop before peer disowns us"
        )


def guarded_handoff(
    snapshot: StatusSnapshot,
    peers: list[PeerAuthCache],
    max_replica_lag: float,
    self_check_interval: float,
) -> str:
    assert_self_authorized(snapshot, peers, max_replica_lag, self_check_interval)
    return "delegation_token_issued"
