# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-agent-passport-as-revoked-when-the-revocation-record-itself-is-only-reachable-through-the-pas.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-agent-passport-as-revoked-when-the-revocation-record-itself-is-only-reachable-through-the-pas.warrant.json
# Markdown SHA-256:   a7b163417b34033d5e4d99dbfe862231640282a3c26735b59bd20deda4e8ffbc
# Code AST SHA-256:   89088bb62516a37b94d7cf14d4d060b02be34d01fd63c3642ca051834661ae69
# Verified Classes:   RevocationFederationError, AuthState, TreeHead, Passport, VerifierPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class RevocationFederationError(RuntimeError):
    """Raised when a passport's revocation status cannot be independently confirmed."""


class AuthState(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


@dataclass
class TreeHead:
    tree_size: int
    signed_at: float
    signature_ok: bool


@dataclass
class Passport:
    passport_id: str
    issuer: str
    revocation_uri: str          # issuer-controlled, self-referential
    expires_at: float
    signature_ok: bool


@dataclass
class VerifierPolicy:
    max_staleness_seconds: float = 300.0
    privileged_actions: frozenset = field(
        default_factory=lambda: frozenset({"settle", "transfer", "grant"})
    )


def check_revocation(
    passport: Passport,
    action: str,
    independent_tree_head: Optional[TreeHead],
    last_known_revoked_ids: frozenset,
    policy: VerifierPolicy,
    now: Optional[float] = None,
) -> AuthState:
    now = now if now is not None else time.time()

    if not passport.signature_ok:
        return AuthState.REVOKED
    if now >= passport.expires_at:
        return AuthState.REVOKED
    if passport.passport_id in last_known_revoked_ids:
        return AuthState.REVOKED

    # Independent witness channel is the only acceptable evidence of non-revocation.
    if independent_tree_head is None or not independent_tree_head.signature_ok:
        return AuthState.UNKNOWN

    staleness = now - independent_tree_head.signed_at
    if staleness > policy.max_staleness_seconds:
        return AuthState.UNKNOWN

    # Circular-trust guard: if the *only* revocation channel is inside the passport
    # itself, we cannot upgrade UNKNOWN to VALID on that channel's silence.
    if independent_tree_head.tree_size < 0:
        return AuthState.UNKNOWN

    return AuthState.VALID


def authorize(
    passport: Passport,
    action: str,
    independent_tree_head: Optional[TreeHead],
    last_known_revoked_ids: frozenset,
    policy: VerifierPolicy,
) -> AuthState:
    state = check_revocation(
        passport, action, independent_tree_head, last_known_revoked_ids, policy
    )

    is_privileged = action in policy.privileged_actions

    if state is AuthState.UNKNOWN and is_privileged:
        # Fail closed on privileged actions when revocation cannot be witnessed.
        raise RevocationFederationError(
            f"Passport {passport.passport_id} revocation status UNKNOWN for "
            f"privileged action '{action}'; independent tree head missing or stale. "
            f"Denying per fail-closed invariant."
        )

    if state is AuthState.UNKNOWN:
        # Non-privileged: allow but caller MUST tag memory as provisional.
        return AuthState.UNKNOWN

    return state


def persist_action_record(
    passport: Passport,
    action: str,
    auth_state: AuthState,
    tree_head: Optional[TreeHead],
) -> dict:
    if auth_state is AuthState.REVOKED:
        raise RevocationFederationError(
            f"Refusing to persist record for revoked passport {passport.passport_id}."
        )
    if auth_state is AuthState.UNKNOWN and action in {"settle", "transfer", "grant"}:
        raise RevocationFederationError(
            f"Refusing to persist privileged record for {passport.passport_id} "
            f"under UNKNOWN authorization."
        )
    return {
        "passport_id": passport.passport_id,
        "action": action,
        "authorization_state": auth_state.value,
        "tree_size_at_check": tree_head.tree_size if tree_head else None,
        "distillable": auth_state is AuthState.VALID,
    }
