# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-token-whose-delegated-scope-chain-terminates-in-a-revoked-intermediate-principal.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-token-whose-delegated-scope-chain-terminates-in-a-revoked-intermediate-principal.warrant.json
# Markdown SHA-256:   67eccb714624e7747ac7f735c4d17504fe78fa498f040809989803946e520c00
# Code AST SHA-256:   fc4b3f5a85f8f90c0efdecf19bbd2890031f1a2fa2e34f0a0962472120e9d400
# Verified Classes:   ChainRevocationError, Link, AAIFToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ChainRevocationError(RuntimeError):
    """Raised when a delegation chain contains a revoked or unverifiable intermediate."""


@dataclass
class Link:
    principal: str
    issuer: str
    expires_at: float
    scope: set[str]


@dataclass
class AAIFToken:
    leaf_principal: str
    audience: str
    expires_at: float
    scope: set[str]
    chain: list[Link]


def verify_chain(
    token: AAIFToken,
    now: float,
    revocation_lookup,
    max_revocation_age: float,
    revocation_age: float,
) -> None:
    if revocation_age > max_revocation_age:
        raise ChainRevocationError(
            f"revocation state stale: age={revocation_age:.1f}s "
            f"> max={max_revocation_age:.1f}s; failing closed"
        )
    for depth, link in enumerate(token.chain):
        if link.expires_at <= now:
            raise ChainRevocationError(
                f"chain link {depth} ({link.principal}) expired at {link.expires_at}"
            )
        status = revocation_lookup(link.principal, link.issuer)
        if status is None:
            raise ChainRevocationError(
                f"revocation status unknown for {link.principal} "
                f"(issuer={link.issuer}) at depth {depth}; failing closed"
            )
        if status.revoked:
            raise ChainRevocationError(
                f"chain link {depth} ({link.principal}) revoked by "
                f"{link.issuer} at {status.revoked_at}; leaf token must be rejected"
            )


def admit(token: AAIFToken, request_scope: set[str], now: float, **kw) -> bool:
    if token.expires_at <= now:
        return False
    if not request_scope.issubset(token.scope):
        return False
    verify_chain(token, now, **kw)
    return True
