# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-credential-was-revoked-mid-handoff-when-the-revocation-event-and-the-in-flight-handoff-cross-on-the-wire.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-credential-was-revoked-mid-handoff-when-the-revocation-event-and-the-in-flight-handoff-cross-on-the-wire.warrant.json
# Markdown SHA-256:   47fde89253c47337824582a799a781a9b8602522b33e28525c1beea5bdb45cae
# Code AST SHA-256:   c4660cabdcf26a218768a0329d919db185555af5d4b0421178327ae8ff4ceae5
# Verified Classes:   RevocationShadowError, Warrant, RevocationView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevocationShadowError(RuntimeError):
    """Raised when a warrant is presented for acceptance or extension while the
    receiver's revocation view is too stale to soundly infer 'not revoked'."""


@dataclass
class Warrant:
    warrant_id: str
    parent_id: str | None
    not_after: float
    minted_at_seen_epoch: int  # minter's last_seen_epoch at mint time
    revoked: bool = False


@dataclass
class RevocationView:
    last_seen_epoch: int
    p_max: float  # WIA-advertised max propagation window, seconds
    epoch_clock: float = field(default_factory=time.monotonic)

    def age(self) -> float:
        return time.monotonic() - self.epoch_clock

    def is_fresh(self) -> bool:
        return self.age() < self.p_max


def validate_for_extension(
    warrant: Warrant,
    chain: dict[str, Warrant],
    view: RevocationView,
    now: float,
) -> None:
    # 1. Chain walk: a revoked ancestor kills every descendant.
    node: Warrant | None = warrant
    seen: set[str] = set()
    while node is not None:
        if node.warrant_id in seen:
            raise RevocationShadowError(f"cycle in warrant chain at {node.warrant_id}")
        seen.add(node.warrant_id)
        if node.revoked:
            raise RevocationShadowError(
                f"ancestor {node.warrant_id} revoked; refusing to extend {warrant.warrant_id}"
            )
        if node.not_after <= now:
            raise RevocationShadowError(f"warrant {node.warrant_id} expired")
        node = chain.get(node.parent_id) if node.parent_id else None

    # 2. Bounded uncertainty: refuse to extend across the propagation shadow.
    if not view.is_fresh():
        raise RevocationShadowError(
            f"revocation view stale by {view.age():.2f}s > P_max={view.p_max}s; "
            f"cannot soundly infer non-revocation for {warrant.warrant_id}"
        )

    # 3. Minter staleness: a child minted by a stale parent is suspect.
    if warrant.minted_at_seen_epoch < view.last_seen_epoch - 1:
        raise RevocationShadowError(
            f"warrant {warrant.warrant_id} minted at seen_epoch="
            f"{warrant.minted_at_seen_epoch}, receiver at {view.last_seen_epoch}; "
            f"minter may have minted inside the shadow"
        )


def reconcile_on_reconnect(view: RevocationView, wia_since_epoch_fn) -> None:
    """Must be called on every listener reconnect. A reconnect without
    reconciliation is a silent revocation gap."""
    missed = wia_since_epoch_fn(view.last_seen_epoch)
    if missed is None:
        raise RevocationShadowError("WIA does not support since_epoch replay; cannot reconcile")
    for record in missed:
        # caller applies records to local store; here we only advance the epoch
        view.last_seen_epoch = max(view.last_seen_epoch, record["epoch"])
    view.epoch_clock = time.monotonic()
