# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-manifest-whose-signing-key-was-rotated-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-manifest-whose-signing-key-was-rotated-mid-handshake.warrant.json
# Markdown SHA-256:   6d66c33b69db5c2fab93e7a1472051e2323d103cb4f076d438bd6107a8965311
# Code AST SHA-256:   e0e4023f0fa1b590170b9c782568a90a3c070ce97040251be5d8ec1f9b7fdc8b
# Verified Classes:   StaleAnchorEpoch, Anchor, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAnchorEpoch(RuntimeError):
    """Raised when a manifest's anchor epoch is behind the verifier's
    refreshed anchor set, or the anchor is too stale for the warrant scope."""
    pass


@dataclass
class Anchor:
    epoch: int
    fetched_at: float
    revoked_kids: frozenset


@dataclass
class Manifest:
    kid: str
    anchor_epoch: int
    warrant_scope: str  # "low" or "elevated"
    signature_valid: bool


ELEVATED = "elevated"


def verify_manifest(manifest: Manifest, anchor: Anchor, staleness_budget_s: float,
                    refresh_fn) -> bool:
    now = time.time()

    # If the anchor is stale, an elevated-warrant manifest must not ride the cache.
    if now - anchor.fetched_at > staleness_budget_s:
        if manifest.warrant_scope == ELEVATED:
            anchor = refresh_fn()  # fail-closed path: must get a fresh anchor
            if now - anchor.fetched_at > staleness_budget_s:
                raise StaleAnchorEpoch(
                    f"anchor still stale after refresh; refusing elevated manifest "
                    f"for kid={manifest.kid}"
                )

    if manifest.kid in anchor.revoked_kids:
        raise StaleAnchorEpoch(
            f"kid={manifest.kid} is revoked in anchor epoch {anchor.epoch}"
        )

    # The temporal binding: the manifest must not predate the anchor we trust.
    if manifest.anchor_epoch < anchor.epoch:
        raise StaleAnchorEpoch(
            f"manifest anchor_epoch={manifest.anchor_epoch} behind "
            f"verifier anchor epoch={anchor.epoch} for kid={manifest.kid}"
        )

    if not manifest.signature_valid:
        raise StaleAnchorEpoch(f"signature invalid for kid={manifest.kid}")

    return True
