# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-cached-revocation-epoch-as-authoritative-before-accepting-a-cross-org-tool-call-and-where-does-propa.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-cached-revocation-epoch-as-authoritative-before-accepting-a-cross-org-tool-call-and-where-does-propa.warrant.json
# Markdown SHA-256:   293059729b0d2d6af2fcb644734311696fbfcb283bce1d3bb8e7fb61ff74978a
# Code AST SHA-256:   d2bef74f0984c18627ccf2f3a6f52a508f51683648115dde0abf85e400929d3c
# Verified Classes:   StaleRevocationEpochError, RevocationEpoch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationEpochError(RuntimeError):
    """Raised when a peer's revocation epoch cannot be bounded as fresh."""
    pass


@dataclass
class RevocationEpoch:
    peer_id: str
    epoch_number: int
    issued_at: float          # RA-signed issuance time, not fetch time
    max_epoch_age: float      # RA-signed staleness tolerance
    signature_valid: bool


def authorize_cross_org_call(
    peer: RevocationEpoch,
    now: float,
    newest_heartbeat_epoch: int,
    heartbeat_cadence: float,
    action_is_mutating: bool,
) -> bool:
    # Signature must be valid regardless of action class.
    if not peer.signature_valid:
        raise StaleRevocationEpochError(
            f"peer {peer.peer_id}: epoch {peer.epoch_number} signature invalid"
        )

    epoch_age = now - peer.issued_at

    # Heartbeat gap: if we have not seen a heartbeat within 2x cadence,
    # the RA is unreachable and we cannot bound the epoch's freshness.
    if now - peer.issued_at > 2 * heartbeat_cadence and action_is_mutating:
        # Distinguish "old epoch" from "stalled relay": if the newest
        # heartbeat we hold is itself old, the relay is stalled.
        if newest_heartbeat_epoch <= peer.epoch_number:
            raise StaleRevocationEpochError(
                f"peer {peer.peer_id}: no heartbeat beyond epoch "
                f"{peer.epoch_number} within {2 * heartbeat_cadence}s; "
                f"relay likely stalled, cannot bound staleness"
            )

    # The core invariant: enforce on epoch age, NOT cache age.
    if action_is_mutating and epoch_age > peer.max_epoch_age:
        raise StaleRevocationEpochError(
            f"peer {peer.peer_id}: epoch {peer.epoch_number} age "
            f"{epoch_age:.1f}s exceeds RA-signed max_epoch_age "
            f"{peer.max_epoch_age:.1f}s; refusing mutating call"
        )

    # Read-only / idempotent calls tolerate a stale-but-signed epoch,
    # but still refuse if the signature is invalid (handled above).
    return True
