# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-delegated-credential-as-revoked-before-the-revocation-record-propagates-to-its-local-trust-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-delegated-credential-as-revoked-before-the-revocation-record-propagates-to-its-local-trust-cache.warrant.json
# Markdown SHA-256:   4ac3ab273c60d240b91c43415b69c8de2bd61c4b211a52e0ee11797eaa7f5e6c
# Code AST SHA-256:   7aa7d58218b06d2a2d161d9f86d86e275adc854b1e18f8df48adce20f6cede06
# Verified Classes:   StaleRevocationCacheError, Credential, CacheEntry, IssuerPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationCacheError(RuntimeError):
    """Raised when a delegation-path credential cannot be validated because
    an ancestor issuer's revocation cache is too stale to be trustworthy."""
    pass


@dataclass
class Credential:
    serial: str
    issuer: str
    parent_serial: str | None
    not_before: float
    not_after: float


@dataclass
class CacheEntry:
    epoch: int
    fetched_at: float
    revoked_serials: frozenset[str]


@dataclass
class IssuerPolicy:
    max_staleness: float | None  # None => unbounded, must re-fetch


def validate_path(
    leaf: Credential,
    path: list[Credential],
    caches: dict[str, CacheEntry],
    policies: dict[str, IssuerPolicy],
    now: float,
    fetch_fn,
) -> bool:
    """Validate a delegated credential by walking the full delegation path.
    Freshness failure at ANY ancestor => refuse (raise), never accept."""
    for cred in path:
        policy = policies.get(cred.issuer)
        cache = caches.get(cred.issuer)

        if policy is None or policy.max_staleness is None:
            # No declared staleness bound: cache is unsound, must re-fetch.
            cache = fetch_fn(cred.issuer)
            caches[cred.issuer] = cache
            if cache is None:
                raise StaleRevocationCacheError(
                    f"issuer {cred.issuer} has no max_staleness and fetch failed"
                )

        age = now - cache.fetched_at
        if age > policy.max_staleness:
            refreshed = fetch_fn(cred.issuer)
            if refreshed is None:
                raise StaleRevocationCacheError(
                    f"issuer {cred.issuer} cache age {age:.1f}s exceeds "
                    f"max_staleness {policy.max_staleness:.1f}s and re-fetch failed"
                )
            cache = refreshed
            caches[cred.issuer] = cache

        if cred.serial in cache.revoked_serials:
            return False  # authoritative revocation observed

    return True
