# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-cached-reputation-warrant-after-its-issuing-aaif-trust-root-revokes-it-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-cached-reputation-warrant-after-its-issuing-aaif-trust-root-revokes-it-mid-handoff.warrant.json
# Markdown SHA-256:   8c18e47e8461b88052659708344a1631a60b6cf616608cc9e55524fb393fb75c
# Code AST SHA-256:   aefa6a127f69bdd70ef9718003b250feea8fff21fc9c4c7e006afc06ac17b806
# Verified Classes:   TrustEpochStale, RevokedWarrant, Warrant, Revocation, FederationState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TrustEpochStale(RuntimeError):
    """Raised when a cached warrant's trust epoch cannot be reconciled with the
    issuing root's currently-observed epoch before an irreversible commit."""


class RevokedWarrant(RuntimeError):
    """Raised when admission is attempted against a warrant that a revocation
    has invalidated, whether or not the signature still verifies."""


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    subject: str
    scope: str
    not_after: float
    epoch: int
    signature_ok: bool = True


@dataclass
class Revocation:
    issuer: str
    subject: str
    scope: str
    effective_at: float
    invalidates_warrant_ids: frozenset = field(default_factory=frozenset)


@dataclass
class FederationState:
    # epoch observed per issuing root; None means "not yet reconciled"
    observed_epoch: dict = field(default_factory=dict)
    # revocations indexed by (issuer, subject, scope) AND by warrant_id
    revocations_by_key: dict = field(default_factory=dict)
    revocations_by_warrant: dict = field(default_factory=dict)
    propagation_sla_seconds: float = 300.0

    def observe_epoch(self, issuer: str, epoch: int) -> None:
        prior = self.observed_epoch.get(issuer)
        if prior is None or epoch > prior:
            self.observed_epoch[issuer] = epoch

    def apply_revocation(self, rev: Revocation) -> None:
        self.revocations_by_key[(rev.issuer, rev.subject, rev.scope)] = rev
        for wid in rev.invalidates_warrant_ids:
            self.revocations_by_warrant[wid] = rev


def admit(
    w: Warrant,
    state: FederationState,
    now: float,
    commit: bool,
) -> str:
    """Three-valued admission. Returns 'ADMIT' | 'REJECT' | 'SUSPEND'.

    `commit=True` marks an irreversible boundary (durable write, baton handoff,
    final answer emission); SUSPEND escalates to REJECT there.
    """
    if not w.signature_ok or now >= w.not_after:
        return "REJECT"

    rev = state.revocations_by_warrant.get(w.warrant_id) or state.revocations_by_key.get(
        (w.issuer, w.subject, w.scope)
    )
    if rev is not None and now >= rev.effective_at:
        if commit:
            raise RevokedWarrant(
                f"warrant {w.warrant_id} revoked by {rev.issuer} at "
                f"{rev.effective_at}, admission attempted at {now}"
            )
        return "REJECT"

    observed = state.observed_epoch.get(w.issuer)
    if observed is None:
        # cannot establish epoch: SUSPEND, and at a commit boundary that is fatal
        if commit:
            raise TrustEpochStale(
                f"cannot establish current epoch for issuer {w.issuer} at commit "
                f"time {now}; warrant {w.warrant_id} epoch={w.epoch} unverified"
            )
        return "SUSPEND"

    if observed != w.epoch:
        # epoch advanced past the warrant's epoch: warrant is stale, re-fetch
        if commit:
            raise TrustEpochStale(
                f"warrant {w.warrant_id} epoch={w.epoch} but issuer {w.issuer} "
                f"observed epoch={observed}; re-fetch before commit"
            )
        return "SUSPEND"

    return "ADMIT"


def run_handoff_loop(
    w: Warrant,
    state: FederationState,
    loop_steps: int,
    step_seconds: float,
    start: float,
) -> None:
    """Provisional admissions mid-loop; mandatory re-verification at commit."""
    now = start
    for step in range(loop_steps):
        verdict = admit(w, state, now, commit=False)
        if verdict == "REJECT":
            raise RevokedWarrant(
                f"warrant {w.warrant_id} rejected mid-loop at step {step} (t={now})"
            )
        if verdict == "SUSPEND":
            # mid-loop: proceed provisionally, but mark the result tainted
            pass
        now += step_seconds

    # irreversible boundary: fail closed
    admit(w, state, now, commit=True)
