# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-has-outlived-its-issuer-s-authority-the-revocation-propagation-lag-window-in-aaif-agent-to-age.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-has-outlived-its-issuer-s-authority-the-revocation-propagation-lag-window-in-aaif-agent-to-age.warrant.json
# Markdown SHA-256:   5bf9540aadf1e4e39ead715783380d19f28507e9f1d7d7ad74f58236ad3320e3
# Code AST SHA-256:   25b6be90e2d8e7cdb9f3b003f5ebfdd2ef5be68c0cee9796c7d1251f95fc6a52
# Verified Classes:   DelegationAuthorityStale, Warrant, RootStatusCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationAuthorityStale(RuntimeError):
    """Raised when a warrant's root authority cannot be confirmed fresh enough to admit."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    root_epoch: int          # root's revocation epoch this warrant was minted against
    not_after: float         # absolute expiry
    delegate: bool


class RootStatusCache:
    """Tracks last-confirmed root revocation epoch and observation time."""
    def __init__(self):
        self._epoch = None
        self._observed_at = None

    def observe(self, epoch: int, now: float):
        self._epoch = epoch
        self._observed_at = now

    def staleness(self, now: float) -> float:
        if self._observed_at is None:
            return float("inf")
        return now - self._observed_at

    @property
    def epoch(self):
        return self._epoch


def admit_warrant(warrant: Warrant, cache: RootStatusCache,
                  delta_max: float, now: float | None = None) -> bool:
    now = time.time() if now is None else now

    # 1. Local expiry still applies.
    if now >= warrant.not_after:
        raise DelegationAuthorityStale(
            f"{warrant.warrant_id}: warrant expired at {warrant.not_after}"
        )

    # 2. Root-status currency is the real gate, independent of TTL.
    if cache.staleness(now) > delta_max:
        raise DelegationAuthorityStale(
            f"{warrant.warrant_id}: root status stale by "
            f"{cache.staleness(now):.1f}s > delta_max={delta_max}s; "
            f"refusing to admit on unconfirmed authority"
        )

    # 3. Epoch mismatch means the root was revoked after this warrant was minted.
    if cache.epoch is not None and warrant.root_epoch < cache.epoch:
        raise DelegationAuthorityStale(
            f"{warrant.warrant_id}: minted at root_epoch={warrant.root_epoch} "
            f"but root has advanced to epoch={cache.epoch}; authority revoked"
        )

    # 4. Clamp effective admission to the freshness horizon, not the TTL.
    effective_deadline = min(warrant.not_after, cache._observed_at + delta_max)
    return now < effective_deadline
