# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-attestation-staleness-after-a-peer-s-permission-revocation-under-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-attestation-staleness-after-a-peer-s-permission-revocation-under-aaif.warrant.json
# Markdown SHA-256:   9dee1e56a7e92b835da2480b95249f3b3deeb8e875518ce7b082f98b1719b470
# Code AST SHA-256:   79e17da7b876a9983d5eccab029a638f0d3ffe761885dad1310f71631c0273e6
# Verified Classes:   StaleAttestationError, CachedAttestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a cached peer attestation is signature-valid but grant-dead."""


@dataclass
class CachedAttestation:
    peer: str
    capability: str
    issued_at: float
    ttl: float
    last_authority_contact: float
    last_authority_verdict: str  # "VALID" | "REVOKED" | "UNKNOWN"


def assert_grant_live(att: CachedAttestation, propagation_window: float, now: float | None = None) -> None:
    now = time.monotonic() if now is None else now

    if att.last_authority_verdict == "REVOKED":
        # Token may still be within TTL; grant is gone. Evict cache and peer health.
        raise StaleAttestationError(
            f"peer {att.peer} capability {att.capability} revoked at authority; "
            f"cached token still has {att.issued_at + att.ttl - now:.3f}s of TTL — do not delegate"
        )

    if att.last_authority_verdict == "UNKNOWN":
        raise StaleAttestationError(
            f"authority unreachable for peer {att.peer}; failing closed on {att.capability}"
        )

    token_age = now - att.issued_at
    contact_age = now - att.last_authority_contact

    if token_age >= att.ttl:
        raise StaleAttestationError(
            f"peer {att.peer} attestation for {att.capability} expired (age {token_age:.3f}s >= ttl {att.ttl:.3f}s)"
        )

    if contact_age > propagation_window:
        # The dangerous band: token fresh, grant liveness unverified.
        raise StaleAttestationError(
            f"peer {att.peer} attestation is token-fresh (age {token_age:.3f}s) but authority contact "
            f"is {contact_age:.3f}s old, exceeding propagation window {propagation_window:.3f}s — "
            f"grant liveness unverified"
        )


def delegate(att: CachedAttestation, propagation_window: float, invoke) -> object:
    try:
        assert_grant_live(att, propagation_window)
    except StaleAttestationError:
        # Evict the cached attestation; do NOT mark the peer unhealthy.
        raise
    return invoke(att.peer, att.capability)
