# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-verified-aaif-attestation-chain-as-insufficient-for-cross-org-action-the-revocation-propagation-lag-window-at-chain-veri.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-verified-aaif-attestation-chain-as-insufficient-for-cross-org-action-the-revocation-propagation-lag-window-at-chain-veri.warrant.json
# Markdown SHA-256:   120badd9fe1205aa4a4bcdf6f53a4b048f7e601e902bacb349615f64afb128da
# Code AST SHA-256:   cf670f1b4793b2635f2c65111cc6d818b37533a3448207636fbe2905b6d4349b
# Verified Classes:   StaleRevocationStateError, RevocationVerdict, AttestationChain
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional


class StaleRevocationStateError(RuntimeError):
    """Raised when a verified attestation chain cannot be admitted because the
    verifier's revocation knowledge for the terminal issuer is older than the
    action's freshness bound."""
    pass


@dataclass
class RevocationVerdict:
    clean: bool
    as_of: datetime          # when this verdict was actually established
    issuer: str


@dataclass
class AttestationChain:
    terminal_issuer: str
    can_delegate: bool
    scope: str
    signature_valid: bool
    not_after: datetime


# Blast-radius-derived staleness bounds, in seconds, per action class.
FRESHNESS_BOUND_SECONDS = {
    "read_public_metadata": 3600,
    "write_state": 300,
    "purge_index": 30,
    "delegate_warrant": 5,   # delegation races compound across hops
}


def admit_chain(
    chain: AttestationChain,
    verdict: RevocationVerdict,
    action: str,
    now: datetime,
) -> None:
    if not chain.signature_valid:
        raise StaleRevocationStateError(f"chain signature invalid for {chain.terminal_issuer}")
    if now > chain.not_after:
        raise StaleRevocationStateError(f"chain expired at {chain.not_after.isoformat()}")

    # Delegation collapses the freshness bound regardless of declared action,
    # because a stale-but-valid delegation can mint warrants that outlive revocation.
    bound_key = "delegate_warrant" if chain.can_delegate else action
    bound = FRESHNESS_BOUND_SECONDS.get(bound_key)
    if bound is None:
        raise StaleRevocationStateError(f"no freshness bound defined for action {bound_key!r}")

    if verdict.issuer != chain.terminal_issuer:
        raise StaleRevocationStateError(
            f"revocation verdict issuer {verdict.issuer!r} does not match chain issuer "
            f"{chain.terminal_issuer!r}"
        )

    age = (now - verdict.as_of).total_seconds()
    if not verdict.clean:
        raise StaleRevocationStateError(
            f"issuer {chain.terminal_issuer!r} key set is revoked"
        )
    if age > bound:
        raise StaleRevocationStateError(
            f"revocation knowledge for {chain.terminal_issuer!r} is {age:.0f}s old, "
            f"exceeds {bound}s bound for action {bound_key!r}; re-fetch required"
        )
    # Admissible: signatures valid, in scope, and revocation knowledge fresh
    # enough for this action's blast radius.
    return None


def try_admit(
    chain: AttestationChain,
    verdict: RevocationVerdict,
    action: str,
    now: datetime,
) -> str:
    try:
        admit_chain(chain, verdict, action, now)
        return "admitted"
    except StaleRevocationStateError as exc:
        # Caller must re-fetch synchronously or deny; never silently downgrade to clean.
        return f"denied: {exc}"


if __name__ == "__main__":
    now = datetime(2025, 6, 11, 12, 0, 0)
    chain = AttestationChain(
        terminal_issuer="org-b-root",
        can_delegate=False,
        scope="purge_index",
        signature_valid=True,
        not_after=now + timedelta(hours=1),
    )
    stale = RevocationVerdict(
        clean=True,
        as_of=now - timedelta(minutes=40),   # the observed failure window
        issuer="org-b-root",
    )
    print(try_admit(chain, stale, "purge_index", now))
    # -> denied: revocation knowledge for 'org-b-root' is 2400s old, exceeds 30s bound ...
