# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revocation-shadow-across-a-delegated-aaif-capability-chain-when-the-intermediate-delegator-never-re-validates.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revocation-shadow-across-a-delegated-aaif-capability-chain-when-the-intermediate-delegator-never-re-validates.warrant.json
# Markdown SHA-256:   5085f0f35a0bac3b91a6cc43362458c2f2c2b2fd99d58fc326721e9f2ab3036a
# Code AST SHA-256:   83c36f27cb76717662fd91b0a0ba41bec657f50a206f4fd6060fbbbada9e6768
# Verified Classes:   RevocationShadowError, CapabilityToken, RevocationList
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RevocationShadowError(RuntimeError):
    """Raised when a delegated capability chain cannot prove full-chain,
    epoch-current non-revocation and therefore sits in a revocation shadow."""
    pass


@dataclass
class CapabilityToken:
    token_id: str
    issuer: str
    scope: str
    expires_at: float
    parent_id: Optional[str] = None
    signature_valid: bool = True


@dataclass
class RevocationList:
    epoch: int
    revoked_ids: set = field(default_factory=set)


def validate_chain(
    leaf: CapabilityToken,
    chain_by_id: dict,
    rl: RevocationList,
    validator_epoch: int,
) -> bool:
    # Collect every ancestor ID from the embedded proof chain.
    ancestor_ids = []
    cursor = leaf.parent_id
    while cursor is not None:
        ancestor = chain_by_id.get(cursor)
        if ancestor is None:
            # Unresolvable ancestor == indistinguishable from revoked. Fail closed.
            raise RevocationShadowError(
                f"ancestor {cursor} unresolvable; cannot prove non-revocation"
            )
        ancestor_ids.append(cursor)
        cursor = ancestor.parent_id

    # Epoch must be at least as new as the RL we are trusting.
    if validator_epoch < rl.epoch:
        raise RevocationShadowError(
            f"validator epoch {validator_epoch} < RL epoch {rl.epoch}; "
            f"stale RL reproduces the shadow"
        )

    # Full-chain revocation check, not leaf-only.
    for tid in [leaf.token_id, *ancestor_ids]:
        if tid in rl.revoked_ids:
            raise RevocationShadowError(
                f"token {tid} revoked at epoch {rl.epoch}; "
                f"leaf {leaf.token_id} is in a revocation shadow"
            )

    # TTL monotonicity: leaf must not outlive any ancestor.
    for tid in ancestor_ids:
        if leaf.expires_at > chain_by_id[tid].expires_at:
            raise RevocationShadowError(
                f"leaf {leaf.token_id} outlives ancestor {tid}; "
                f"shadow duration unbounded by root TTL"
            )

    if not leaf.signature_valid:
        raise RevocationShadowError(f"leaf {leaf.token_id} signature invalid")

    return True
