# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-revocation-status-as-fresh-enough-to-act-on-a-delegated-warrant-across-an-organizational-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-revocation-status-as-fresh-enough-to-act-on-a-delegated-warrant-across-an-organizational-boundar.warrant.json
# Markdown SHA-256:   19e85667e2aaa49558c644920c4f44cce2693089c2a93fd29d61359d36342014
# Code AST SHA-256:   145c07837913e43c48bfa1e47937baad5fd27886342ba0c473a66f502b3dee43
# Verified Classes:   RevocationFreshnessError, RiskHorizon, RevocationAssertion, DelegatedWarrant, VerificationReceipt
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class RevocationFreshnessError(RuntimeError):
    """Raised when a verifier cannot bound the freshness of a revocation
    assertion tightly enough for the risk horizon of the pending action."""
    pass


class RiskHorizon(Enum):
    READ_ONLY = 300.0        # seconds of tolerated staleness
    STATEFUL_REVERSIBLE = 60.0
    IRREVERSIBLE = 0.0       # must re-verify live, immediately before acting


@dataclass
class RevocationAssertion:
    issuer: str
    status: str              # "good" | "revoked" | "unknown"
    this_update: float       # responder's signing time (epoch seconds)
    next_update: float       # responder's declared validity end
    responder_freshness_bound: float  # max age responder itself may serve


@dataclass
class DelegatedWarrant:
    signer: str
    issued_at: float
    expires_at: float
    declared_max_staleness: float
    chain_issuers: list      # full issuer chain, leaf-first


@dataclass
class VerificationReceipt:
    warrant_signer: str
    action: str
    verified_at: float
    assertion_age: float
    chain_revalidated: bool


def verify_before_action(
    warrant: DelegatedWarrant,
    assertion: RevocationAssertion,
    risk: RiskHorizon,
    now: float,
    clock_skew_budget: float = 5.0,
    live_fetch: bool = False,
) -> VerificationReceipt:
    # 1. Warrant must still be live.
    if now >= warrant.expires_at:
        raise RevocationFreshnessError(
            f"warrant from {warrant.signer} expired at {warrant.expires_at}"
        )

    # 2. Responder freshness: a signed-but-stale assertion is a failure.
    assertion_age = now - assertion.this_update
    if assertion_age < -clock_skew_budget:
        raise RevocationFreshnessError(
            f"assertion thisUpdate {assertion.this_update} is in the future "
            f"beyond skew budget {clock_skew_budget}"
        )
    if assertion_age > assertion.responder_freshness_bound:
        raise RevocationFreshnessError(
            f"responder freshness bound {assertion.responder_freshness_bound}s "
            f"exceeded by assertion age {assertion_age}s"
        )

    # 3. Status must be affirmatively good; unknown/revoked is a hard stop.
    if assertion.status != "good":
        raise RevocationFreshnessError(
            f"issuer {assertion.issuer} status={assertion.status}; refusing to act"
        )

    # 4. Freshness budget: min of cache validity, responder bound, warrant life,
    #    and the action's risk horizon. Irreversible actions force a live fetch.
    max_staleness = min(
        assertion.next_update - now,
        assertion.responder_freshness_bound,
        warrant.expires_at - now,
        risk.value,
        warrant.declared_max_staleness,
    )
    if risk is RiskHorizon.IRREVERSIBLE and not live_fetch:
        raise RevocationFreshnessError(
            f"irreversible action '{warrant.signer}' requires a live revocation "
            f"fetch; cached assertion age {assertion_age}s is not admissible"
        )
    if assertion_age > max_staleness:
        raise RevocationFreshnessError(
            f"assertion age {assertion_age}s exceeds admissible staleness "
            f"{max_staleness}s for risk horizon {risk.name}"
        )

    # 5. Transitive chain revalidation: every issuer must be re-checked, and
    #    any issuer revoked after a downstream warrant was issued voids it.
    for issuer in warrant.chain_issuers:
        if issuer == assertion.issuer:
            continue
        # In production this dispatches a per-issuer fetch; here we require the
        # caller to have supplied a fresh assertion for every hop.
        raise RevocationFreshnessError(
            f"issuer {issuer} in delegation chain was not revalidated; "
            f"transitive revocation cannot be bounded"
        )

    return VerificationReceipt(
        warrant_signer=warrant.signer,
        action=risk.name,
        verified_at=now,
        assertion_age=assertion_age,
        chain_revalidated=True,
    )
