# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-trust-anchor-whose-policy-epoch-has-advanced-past-its-own-knowledge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-trust-anchor-whose-policy-epoch-has-advanced-past-its-own-knowledge.warrant.json
# Markdown SHA-256:   d042daf67c90d2b3f1e672fdee13230bc53086f8c9359b35d6e171377ed093bd
# Code AST SHA-256:   2b40a9f4d0badc25ec463a70e341e6a97c0a1c0c7e2306e45c9e9feb2aa3b7b4
# Verified Classes:   EpochSkewViolation, TrustAnchor, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochSkewViolation(RuntimeError):
    """Raised when a federated warrant's policy epoch cannot be satisfied by the verifier's anchor knowledge."""
    pass


@dataclass(frozen=True)
class TrustAnchor:
    issuer: str
    epoch: int
    rotation_cadence_s: int
    fetched_at: float


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject_agent: str
    policy_epoch_min: int
    signature_valid: bool


def accept_federated_warrant(
    warrant: Warrant,
    cached_anchor: TrustAnchor,
    fetch_anchor,          # callable(issuer) -> TrustAnchor, synchronous, may raise
    now: float = None,
) -> bool:
    now = time.time() if now is None else now

    if not warrant.signature_valid:
        raise EpochSkewViolation(
            f"warrant for {warrant.subject_agent} failed signature check; "
            f"cannot proceed to epoch evaluation"
        )

    # Invariant 1: verifier's cache TTL must be strictly tighter than issuer cadence.
    # A verifier that cannot bound its own staleness must not accept federated warrants.
    cache_age = now - cached_anchor.fetched_at
    if cache_age >= cached_anchor.rotation_cadence_s:
        # Cache is older than one full rotation: known epoch may already be stale.
        # Force re-fetch before any acceptance decision.
        cached_anchor = fetch_anchor(warrant.issuer)

    # Invariant 2: the warrant's declared minimum policy epoch is a freshness demand.
    # If the verifier's known epoch is behind it, the verifier MUST re-fetch, not accept.
    if warrant.policy_epoch_min > cached_anchor.epoch:
        refreshed = fetch_anchor(warrant.issuer)
        if refreshed.epoch < warrant.policy_epoch_min:
            raise EpochSkewViolation(
                f"issuer {warrant.issuer} minted warrant at policy_epoch_min="
                f"{warrant.policy_epoch_min} but current anchor epoch is "
                f"{refreshed.epoch}; issuer signer is ahead of its own anchor "
                f"(clock skew or compromised signer)"
            )
        cached_anchor = refreshed

    # Invariant 3: reject warrants demanding a future epoch beyond the issuer's current.
    if warrant.policy_epoch_min > cached_anchor.epoch:
        raise EpochSkewViolation(
            f"warrant demands epoch {warrant.policy_epoch_min} > known "
            f"{cached_anchor.epoch} after refresh; refusing acceptance"
        )

    # Only now is signature-validity sufficient for acceptance.
    return True


def negotiate_interdomain_policy(
    verifier_ttl_s: int,
    issuer_anchor: TrustAnchor,
) -> int:
    """Return the maximum safe cache TTL for an issuer's anchor."""
    if verifier_ttl_s >= issuer_anchor.rotation_cadence_s:
        raise EpochSkewViolation(
            f"configured TTL {verifier_ttl_s}s >= issuer cadence "
            f"{issuer_anchor.rotation_cadence_s}s for {issuer_anchor.issuer}; "
            f"this guarantees a revocation-bypass window of "
            f"{verifier_ttl_s - issuer_anchor.rotation_cadence_s}s per rotation. "
            f"Refusing to negotiate policy."
        )
    return verifier_ttl_s
