# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cryptographically-valid-peer-warrant-as-revoked-when-the-revocation-event-has-not-yet-crossed-the-trust.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-cryptographically-valid-peer-warrant-as-revoked-when-the-revocation-event-has-not-yet-crossed-the-trust.warrant.json
# Markdown SHA-256:   4502bf1f4f236ed22c80eb99d6df619725af09261ccd8ad21feb2d348e2fabcb
# Code AST SHA-256:   e814593d996c3f5af01e6592755f959613ebc7c7e84ce810247effee51dcf76c
# Verified Classes:   WarrantVerdictError, Verdict, KeyState, IssuerView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class WarrantVerdictError(RuntimeError):
    """Raised when a warrant cannot be resolved to a definitive verdict."""


class Verdict(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    INDETERMINATE = "indeterminate"


@dataclass(frozen=True)
class KeyState:
    kid: str
    present_in_set: bool
    marked_revoked: bool


@dataclass(frozen=True)
class IssuerView:
    issuer: str
    last_confirmed_fetch: float          # monotonic seconds
    published_bound: float               # issuer's propagation bound for this key class
    known_revocation_epoch: int
    keys: dict[str, KeyState]


def verify_warrant(
    view: IssuerView,
    kid: str,
    signature_ok: bool,
    warrant_epoch: int,
    now: float,
) -> Verdict:
    if not signature_ok:
        # A bad signature is a definitive rejection, not an indeterminate state.
        return Verdict.REVOKED

    age = now - view.last_confirmed_fetch
    if age > view.published_bound:
        # We cannot assert freshness; signature validity is necessary but insufficient.
        return Verdict.INDETERMINATE

    if warrant_epoch < view.known_revocation_epoch:
        # Issuer has advanced its revocation epoch past this warrant's mint epoch.
        return Verdict.REVOKED

    key = view.keys.get(kid)
    if key is None or not key.present_in_set:
        # Within bound and key absent: the issuer has removed it; treat as revoked.
        return Verdict.REVOKED
    if key.marked_revoked:
        return Verdict.REVOKED

    return Verdict.VALID


def authorize_handoff(
    view: IssuerView,
    kid: str,
    signature_ok: bool,
    warrant_epoch: int,
    now: float,
    refetch,
    refetch_timeout: float,
) -> Verdict:
    verdict = verify_warrant(view, kid, signature_ok, warrant_epoch, now)

    if verdict is Verdict.INDETERMINATE:
        # Blocking freshness pull; fail closed if it cannot complete within bound.
        fresh_view = refetch(timeout=refetch_timeout)
        if fresh_view is None:
            raise WarrantVerdictError(
                f"cannot establish freshness for issuer={view.issuer} kid={kid} "
                f"within bound={view.published_bound}s; refusing handoff"
            )
        verdict = verify_warrant(
            fresh_view, kid, signature_ok, warrant_epoch, now
        )
        if verdict is Verdict.INDETERMINATE:
            raise WarrantVerdictError(
                f"post-refetch freshness still unestablished for issuer={view.issuer} kid={kid}"
            )

    if verdict is Verdict.REVOKED:
        raise WarrantVerdictError(
            f"warrant rejected for issuer={view.issuer} kid={kid} "
            f"warrant_epoch={warrant_epoch} known_epoch={view.known_revocation_epoch}"
        )

    return verdict
