# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-revoked-aaif-warrant-is-still-being-honored-across-a-partitioned-trust-domain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-revoked-aaif-warrant-is-still-being-honored-across-a-partitioned-trust-domain.warrant.json
# Markdown SHA-256:   4593121d67d9e8b36c4b75df58a7845991ffefaad1d2d7043259641bb2f859e4
# Code AST SHA-256:   d01df2a13caa64933af3564b326f1ad8ae4a5ef5b3fb1456326e19ba54d37a1f
# Verified Classes:   StaleWarrantError, ByzantineFreshnessError, Capability, Warrant, RevocationCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a warrant's revocation freshness cannot be established
    within the capability's max_staleness bound."""
    pass


class ByzantineFreshnessError(RuntimeError):
    """Raised when cross-domain freshness proofs disagree beyond the
    tolerated Byzantine fraction."""
    pass


@dataclass
class Capability:
    name: str
    max_staleness_seconds: int  # signed by issuer; verifier cannot relax


@dataclass
class Warrant:
    agent_id: str
    issuer_domain: str
    signing_key_id: str
    not_before: float
    not_after: float
    capabilities: list[Capability]
    signature_valid: bool  # set by signature check, not trusted from wire


@dataclass
class RevocationCache:
    last_successful_pull: float
    last_known_epoch: str
    freshness_proofs: dict  # domain -> (epoch, timestamp, signed_by)


def verify_warrant(
    warrant: Warrant,
    cache: RevocationCache,
    now: float,
    required_corroboration: int = 1,
) -> bool:
    # 1. Signature validity (local predicate)
    if not warrant.signature_valid:
        raise StaleWarrantError(
            f"signature invalid for {warrant.agent_id}; cannot proceed"
        )

    # 2. Window validity (local predicate)
    if not (warrant.not_before <= now <= warrant.not_after):
        raise StaleWarrantError(
            f"warrant for {warrant.agent_id} outside validity window"
        )

    # 3. Freshness: per-capability, fail closed
    cache_age = now - cache.last_successful_pull
    for cap in warrant.capabilities:
        if cache_age > cap.max_staleness_seconds:
            # Distinguish "no proof at all" from "proof too old"
            proof = cache.freshness_proofs.get(warrant.issuer_domain)
            if proof is None:
                raise StaleWarrantError(
                    f"no freshness proof for {warrant.agent_id} "
                    f"capability {cap.name}; cache age {cache_age:.0f}s "
                    f"> max_staleness {cap.max_staleness_seconds}s"
                )
            proof_age = now - proof[1]
            if proof_age > cap.max_staleness_seconds:
                raise StaleWarrantError(
                    f"freshness proof for {warrant.agent_id} "
                    f"capability {cap.name} is {proof_age:.0f}s old, "
                    f"exceeds max_staleness {cap.max_staleness_seconds}s"
                )

    # 4. Byzantine corroboration for high-blast-radius capabilities
    high_blast = [c for c in warrant.capabilities if c.max_staleness_seconds <= 60]
    if high_blast:
        proofs = cache.freshness_proofs
        if len(proofs) < required_corroboration:
            raise ByzantineFreshnessError(
                f"insufficient corroboration for {warrant.agent_id}: "
                f"{len(proofs)} proofs, need {required_corroboration}"
            )
        epochs = {p[0] for p in proofs.values()}
        if len(epochs) > 1:
            # Disagreement among domains; cannot resolve, fail closed
            raise ByzantineFreshnessError(
                f"freshness proof disagreement for {warrant.agent_id}: "
                f"epochs {epochs}"
            )

    return True


def accept_or_reject(warrant, cache, now, corroboration=1):
    try:
        verify_warrant(warrant, cache, now, corroboration)
        return "ACCEPT"
    except StaleWarrantError as e:
        # Fail closed; log with capability context for audit
        return f"REJECT_STALE: {e}"
    except ByzantineFreshnessError as e:
        return f"REJECT_BYZANTINE: {e}"
