# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-key-during-a-mid-handoff-a2a-exchange-when-the-revocation-propagates-faster-than-the-in-flight-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-key-during-a-mid-handoff-a2a-exchange-when-the-revocation-propagates-faster-than-the-in-flight-warrant.warrant.json
# Markdown SHA-256:   470e38fff2dda95b3348e4b9d55684716744f0103e96e21bd69994e41abebb69
# Code AST SHA-256:   ee9d33110cbcab57bc67de1aa7c5b87f431646c2778d4b516c43ea03b1890334
# Verified Classes:   WarrantAuthorizationError, KeyRecord, KeyCache, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class WarrantAuthorizationError(RuntimeError):
    """Raised when a warrant cannot be proven authorized across its full validity interval."""
    pass


@dataclass
class KeyRecord:
    key_id: str
    public_key: bytes
    valid_from: float
    revoked_at: Optional[float] = None
    retired_at: Optional[float] = None  # deprecation, NOT revocation


@dataclass
class KeyCache:
    records: dict
    fetched_at: float


@dataclass
class Warrant:
    issuer: str
    key_id: str
    iat: float
    exp: float
    signature: bytes


def validate_warrant(
    warrant: Warrant,
    cache: KeyCache,
    now: float,
    refresh_fn,  # callable(issuer) -> KeyCache
) -> KeyRecord:
    if warrant.iat > now:
        raise WarrantAuthorizationError(
            f"warrant iat={warrant.iat} is in the future relative to now={now}"
        )
    if warrant.exp < now:
        raise WarrantAuthorizationError(
            f"warrant expired at {warrant.exp}, consumed at {now}"
        )

    record = cache.records.get(warrant.key_id)

    # Cache predates the warrant: cannot rule out a revocation between
    # warrant.iat and now. Force synchronous refresh.
    if record is None or cache.fetched_at < warrant.iat:
        cache = refresh_fn(warrant.issuer)
        record = cache.records.get(warrant.key_id)
        if record is None:
            raise WarrantAuthorizationError(
                f"key {warrant.key_id} unknown even after refresh from {warrant.issuer}"
            )

    # Interval-overlap test: the ONLY correct revocation predicate.
    # A warrant is dead if its validity interval overlaps the revoked interval.
    if record.revoked_at is not None:
        if warrant.iat <= record.revoked_at <= warrant.exp:
            raise WarrantAuthorizationError(
                f"key {warrant.key_id} revoked at {record.revoked_at} "
                f"overlaps warrant interval [{warrant.iat}, {warrant.exp}]"
            )
        if warrant.iat >= record.revoked_at:
            raise WarrantAuthorizationError(
                f"warrant issued at {warrant.iat} after key revocation at {record.revoked_at}"
            )

    # retired_at (deprecation) does NOT invalidate in-flight warrants.
    # It is intentionally not checked here.

    return record


def consume_handoff(warrant: Warrant, cache: KeyCache, now: float, refresh_fn):
    try:
        record = validate_warrant(warrant, cache, now, refresh_fn)
    except WarrantAuthorizationError:
        # Do NOT distill a trust belief; mark episode retroactively revoked.
        raise
    return record.public_key
