# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-aaif-credential-during-cross-swarm-handoff-and-how-does-stale-revocation-state-compound-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-aaif-credential-during-cross-swarm-handoff-and-how-does-stale-revocation-state-compound-across-agent-hops.warrant.json
# Markdown SHA-256:   9451ddb452aa45d11b3c72938bcb19eea0eb2db922df3ffa1ed09b8f97c34d52
# Code AST SHA-256:   a13561929b057c36d11df293f739dc0817d81efd36f7aa00845789b4563f5320
# Verified Classes:   StaleRevocationBasisError, Credential, TrustRoot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleRevocationBasisError(RuntimeError):
    """Raised when a credential's basis freshness exceeds the propagation budget."""
    pass


@dataclass
class Credential:
    subject: str
    signature_valid: bool
    basis_freshness: float  # epoch seconds when revocation state was last confirmed


@dataclass
class TrustRoot:
    propagation_budget: float  # signed max revocation-to-cache latency, seconds


def verify_attestation(
    cred: Credential,
    root: TrustRoot,
    revocation_set: set[str],
    now: Optional[float] = None,
) -> str:
    """Three-valued verification: VALID | REVOKED | UNKNOWN.

    Collapsing UNKNOWN into VALID is the laundering defect.
    """
    now = now if now is not None else time.time()

    if not cred.signature_valid:
        raise StaleRevocationBasisError(
            f"signature invalid for subject={cred.subject}"
        )

    if cred.subject in revocation_set:
        return "REVOKED"

    age = now - cred.basis_freshness
    if age > root.propagation_budget:
        # Signature is good, but our non-revocation knowledge is too old
        # to be load-bearing. Must NOT return VALID.
        return "UNKNOWN"

    return "VALID"


def mint_warrant(
    delegator: str,
    delegate: Credential,
    root: TrustRoot,
    revocation_set: set[str],
    now: Optional[float] = None,
) -> dict:
    """Mint a derived warrant, propagating basis freshness monotonically."""
    now = now if now is not None else time.time()

    status = verify_attestation(delegate, root, revocation_set, now=now)
    if status == "REVOKED":
        raise StaleRevocationBasisError(
            f"refusing to re-attest revoked subject={delegate.subject}"
        )
    if status == "UNKNOWN":
        # Fail closed: force caller to re-fetch revocation state synchronously.
        raise StaleRevocationBasisError(
            f"cannot mint warrant for subject={delegate.subject}: "
            f"basis age {now - delegate.basis_freshness:.0f}s exceeds "
            f"budget {root.propagation_budget:.0f}s; re-fetch required"
        )

    # CRITICAL: basis_freshness inherits the input's, NOT `now`.
    return {
        "delegator": delegator,
        "subject": delegate.subject,
        "issued_at": now,
        "basis_freshness": delegate.basis_freshness,  # monotonic, never reset
    }


def accept_handoff(
    warrant: dict,
    leaf_cred: Credential,
    root: TrustRoot,
    revocation_set: set[str],
    now: Optional[float] = None,
) -> bool:
    """Auditor validates the leaf credential, not just the upstream warrant."""
    now = now if now is not None else time.time()

    # Re-verify the leaf directly; do not trust transitive warrant coverage.
    leaf_status = verify_attestation(leaf_cred, root, revocation_set, now=now)
    if leaf_status != "VALID":
        raise StaleRevocationBasisError(
            f"handoff rejected: leaf subject={leaf_cred.subject} "
            f"status={leaf_status}"
        )

    basis_age = now - warrant["basis_freshness"]
    if basis_age > root.propagation_budget:
        raise StaleRevocationBasisError(
            f"handoff rejected: warrant basis age {basis_age:.0f}s "
            f"exceeds budget {root.propagation_budget:.0f}s"
        )

    return True
