# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-rotated-aaif-signing-key-mid-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-honor-a-rotated-aaif-signing-key-mid-delegation-chain.warrant.json
# Markdown SHA-256:   734688539fab57bd39bd8df04392d7436a9a61317d97bbdc299fda89e4017dc8
# Code AST SHA-256:   639b63b7e616498bd1b181149466e8029c9fc69548d758fde84029577cc77d89
# Verified Classes:   WarrantAuthorityError, KeySnapshot, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantAuthorityError(RuntimeError):
    """Raised when a warrant's authority horizon is not backed by a live signing key."""


@dataclass(frozen=True)
class KeySnapshot:
    fetched_at: float
    cache_ttl: float
    skew: float
    published: dict  # kid -> (publication_not_before, publication_not_after, epoch)


@dataclass(frozen=True)
class Warrant:
    kid: str
    epoch: int
    not_before: float
    not_after: float
    parent_kid: Optional[str] = None


def resolve_chain_atomically(chain, snapshot: KeySnapshot, now: float) -> None:
    """Verify every hop against ONE snapshot; refuse on any uncertainty band."""
    lo = snapshot.fetched_at - snapshot.skew
    hi = snapshot.fetched_at + snapshot.cache_ttl + snapshot.skew
    if not (lo <= now <= hi):
        # Snapshot too old to trust for this instant: must re-fetch, not guess.
        raise WarrantAuthorityError(
            f"key snapshot stale: now={now} outside confidence [{lo},{hi}]"
        )
    for w in chain:
        entry = snapshot.published.get(w.kid)
        if entry is None:
            raise WarrantAuthorityError(f"kid {w.kid} absent from snapshot; fail closed")
        pub_nb, pub_na, active_epoch = entry
        if w.epoch != active_epoch:
            raise WarrantAuthorityError(
                f"kid {w.kid} epoch {w.epoch} != active {active_epoch}: zombie warrant"
            )
        # Authority horizon is bounded by the SIGNING KEY's publication window,
        # not merely by the warrant's own TTL.
        authority_end = min(w.not_after, pub_na)
        if not (pub_nb <= w.not_before and now + snapshot.skew <= authority_end):
            raise WarrantAuthorityError(
                f"warrant {w.kid} authority [{w.not_before},{authority_end}] "
                f"does not contain now+skew={now + snapshot.skew}"
            )
        # Temporal-splice guard: parent must resolve in the same snapshot.
        if w.parent_kid is not None and w.parent_kid not in snapshot.published:
            raise WarrantAuthorityError(
                f"parent {w.parent_kid} missing from same snapshot: temporal splice"
            )
