# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-present-a-delegated-credential-chain-whose-warrant-epoch-has-advanced-past-its-own-cached-root.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-present-a-delegated-credential-chain-whose-warrant-epoch-has-advanced-past-its-own-cached-root.warrant.json
# Markdown SHA-256:   94a16e842d9ee44cff6d8bf59696a929a1372caa1141264cdc1d60522c2a5f47
# Code AST SHA-256:   c16866d9962a25d8c39fef2a6b44a78eb08b9bb1ed217b59bba8bc791a864418
# Verified Classes:   StaleWarrantEpochError, CachedChain, EpochObservation, DelegatedChainPresenter
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantEpochError(RuntimeError):
    """Raised when an instance would present a chain whose root epoch is not confirmed current."""
    pass


@dataclass
class CachedChain:
    root_epoch: int
    leaf_expires_at: float


@dataclass
class EpochObservation:
    epoch: int
    observed_at: float


class DelegatedChainPresenter:
    def __init__(self, max_staleness_s: float):
        self.max_staleness_s = max_staleness_s
        self._last_obs: EpochObservation | None = None

    def observe_epoch(self, epoch: int, now: float | None = None) -> None:
        now = time.monotonic() if now is None else now
        if self._last_obs is not None and epoch < self._last_obs.epoch:
            # Epoch regression: issuer state went backwards. Treat as unconfirmed.
            self._last_obs = None
            raise StaleWarrantEpochError(
                f"epoch regressed {self._last_obs.epoch}->{epoch}; observation invalidated"
            )
        self._last_obs = EpochObservation(epoch=epoch, observed_at=now)

    def present(self, chain: CachedChain, now: float | None = None) -> CachedChain:
        now = time.monotonic() if now is None else now
        if self._last_obs is None:
            raise StaleWarrantEpochError(
                "no confirmed epoch observation; refusing to present (fail closed)"
            )
        if now - self._last_obs.observed_at > self.max_staleness_s:
            raise StaleWarrantEpochError(
                f"last epoch observation is {now - self._last_obs.observed_at:.1f}s old, "
                f"exceeds max staleness {self.max_staleness_s}s; refusing to present"
            )
        if chain.root_epoch < self._last_obs.epoch:
            raise StaleWarrantEpochError(
                f"chain root epoch {chain.root_epoch} is behind observed epoch "
                f"{self._last_obs.epoch}; refresh required before presentation"
            )
        if chain.root_epoch > self._last_obs.epoch:
            raise StaleWarrantEpochError(
                f"chain root epoch {chain.root_epoch} is ahead of observed epoch "
                f"{self._last_obs.epoch}; observation is behind the chain, re-observe"
            )
        return chain
