# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-revocation-token-it-cannot-verify-stale-signature-acceptance-at-aaif-trust-domain-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-revocation-token-it-cannot-verify-stale-signature-acceptance-at-aaif-trust-domain-boundaries.warrant.json
# Markdown SHA-256:   008df284e6861a60ead15fa667bb321e9282a4d55313c52abab01d7cac0f6fd3
# Code AST SHA-256:   fe675388fcf933b642e45016a211328d6c972aa1a0e3350be13b1713ae8a9c42
# Verified Classes:   IndeterminateRevocationState, AnchorRecord, RevocationToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class IndeterminateRevocationState(RuntimeError):
    """Raised when a revocation token's anchor-of-issuance cannot be linked
    to the relying party's current anchor via a complete supersession chain.

    This is NOT a rejection. It is an explicit signal that the relying party
    must retain its prior admission verdict and alert, rather than infer
    'not revoked' from the absence of a verifiable token.
    """


@dataclass(frozen=True)
class AnchorRecord:
    anchor_id: str
    valid_from: int
    valid_until: Optional[int]  # None = currently authoritative
    supersedes: Optional[str]   # anchor_id this anchor replaces


@dataclass(frozen=True)
class RevocationToken:
    identity: str
    issuance_epoch: int
    anchor_id: str
    signature_valid: bool


def has_supersession_chain(
    anchor_id: str,
    current_anchor_id: str,
    history: dict[str, AnchorRecord],
) -> bool:
    """Walk forward from anchor_id to current_anchor_id via supersedes edges."""
    seen = set()
    cursor = anchor_id
    while cursor != current_anchor_id:
        if cursor in seen:
            return False
        seen.add(cursor)
        rec = history.get(cursor)
        if rec is None or rec.valid_until is None:
            # Reached a leaf that is not the current anchor: chain is broken.
            return False
        # Find the anchor that supersedes this one.
        successor = next(
            (a for a in history.values() if a.supersedes == cursor),
            None,
        )
        if successor is None:
            return False
        cursor = successor.anchor_id
    return True


def evaluate_revocation(
    token: RevocationToken,
    current_anchor_id: str,
    history: dict[str, AnchorRecord],
) -> str:
    """Return 'REVOKED', 'NOT_REVOKED', or raise IndeterminateRevocationState."""
    if not token.signature_valid:
        return "NOT_REVOKED"

    anchor = history.get(token.anchor_id)
    if anchor is None:
        raise IndeterminateRevocationState(
            f"unknown anchor {token.anchor_id!r} for identity {token.identity!r}"
        )

    if not (anchor.valid_from <= token.issuance_epoch):
        raise IndeterminateRevocationState(
            f"token for {token.identity!r} predates anchor {anchor.anchor_id!r}"
        )
    if anchor.valid_until is not None and token.issuance_epoch >= anchor.valid_until:
        raise IndeterminateRevocationState(
            f"token for {token.identity!r} postdates anchor {anchor.anchor_id!r}"
        )

    if not has_supersession_chain(token.anchor_id, current_anchor_id, history):
        raise IndeterminateRevocationState(
            f"no supersession chain from {token.anchor_id!r} to "
            f"{current_anchor_id!r} for identity {token.identity!r}; "
            f"retain prior verdict, do not infer NOT_REVOKED"
        )

    return "REVOKED"


def enforce(
    token: RevocationToken,
    current_anchor_id: str,
    history: dict[str, AnchorRecord],
    prior_verdict: str,
) -> str:
    """Enforcement wrapper: INDETERMINATE must never become NOT_REVOKED."""
    try:
        return evaluate_revocation(token, current_anchor_id, history)
    except IndeterminateRevocationState:
        # Fail closed to the last known-good verdict. Never admit on silence.
        return prior_verdict
