# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-a2a-warrant-as-revoked-when-the-revocation-event-is-causally-younger-than-the-warrant-s-own-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-a2a-warrant-as-revoked-when-the-revocation-event-is-causally-younger-than-the-warrant-s-own-i.warrant.json
# Markdown SHA-256:   081e038ea3343f7cb80afd9f82d4cdf1c02bab9aa67edf36d8a06465f3a14d6c
# Code AST SHA-256:   5564fd98d6624e2f6abc68bb5368ee421515e28be79c308f333d1da372f5b8c0
# Verified Classes:   RevocationPolicyError, KeyState, KeyringEntry, RevocationEvent, MeshVerifier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum


class RevocationPolicyError(RuntimeError):
    """Raised when a verifier applies a policy that is not valid for its mesh configuration."""
    pass


class KeyState(Enum):
    TRUSTED = "trusted"
    SUSPECT = "suspect"      # unverifiable revocation observed; must not authorize new work
    REVOKED = "revoked"
    REFUTED = "refuted"      # revocation claimed but revoking key proven illegitimate


@dataclass
class KeyringEntry:
    key_id: str
    state: KeyState = KeyState.TRUSTED
    suspect_since: float | None = None
    last_confirmed_epoch: int = 0


@dataclass
class RevocationEvent:
    revoked_key_id: str
    revoking_key_id: str
    issuer_epoch: int
    signature_verified: bool
    received_at: float = field(default_factory=time.monotonic)


class MeshVerifier:
    def __init__(self, delta_max_seconds: float, cross_signed_rotations: bool):
        self.delta_max = delta_max_seconds
        self.cross_signed = cross_signed_rotations
        self.keyring: dict[str, KeyringEntry] = {}

    def on_revocation(self, ev: RevocationEvent) -> None:
        entry = self.keyring.get(ev.revoked_key_id)
        if entry is None:
            return  # not in trust set; nothing to do

        # Replay defense: reject events from epochs we've already passed.
        if ev.issuer_epoch < entry.last_confirmed_epoch:
            return

        # Invariant: the *observation* of a revocation-shaped event must
        # downgrade trust, regardless of whether the signature verifies.
        if entry.state is KeyState.TRUSTED:
            entry.state = KeyState.SUSPECT
            entry.suspect_since = ev.received_at

        if ev.signature_verified:
            entry.state = KeyState.REVOKED
            entry.last_confirmed_epoch = ev.issuer_epoch
            return

        # Unverifiable revocation — policy must be valid for mesh config.
        if not self.cross_signed and not self.delta_max:
            raise RevocationPolicyError(
                f"unverifiable revocation for {ev.revoked_key_id} from "
                f"{ev.revoking_key_id} (epoch {ev.issuer_epoch}) on a mesh "
                f"without cross-signed rotations and without a freshness "
                f"contract; no safe policy exists — refusing to continue "
                f"treating the key as trusted"
            )

    def authorize_warrant(self, signing_key_id: str, now: float | None = None) -> bool:
        now = now if now is not None else time.monotonic()
        entry = self.keyring.get(signing_key_id)
        if entry is None:
            return False
        if entry.state is KeyState.REVOKED:
            return False
        if entry.state is KeyState.SUSPECT:
            # Bounded-staleness contract: if we've exceeded delta_max without
            # resolving the pending revocation, we cannot authorize.
            if entry.suspect_since is None:
                raise RevocationPolicyError(
                    f"SUSPECT key {signing_key_id} has no timestamp; state "
                    f"machine is corrupted"
                )
            if self.delta_max and (now - entry.suspect_since) <= self.delta_max:
                return False  # still within resolution window; block anyway
            return False      # window expired; hard-fail, block
        return entry.state is KeyState.TRUSTED
