# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-trust-broker-transit-expiry-during-cross-org-agent-federation-before-propagating-a-delegated-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-trust-broker-transit-expiry-during-cross-org-agent-federation-before-propagating-a-delegated-warrant.warrant.json
# Markdown SHA-256:   430f6dfe82164b81eb01b63f0f06cef7cf7228c380139266d368d06342094365
# Code AST SHA-256:   594cd8ed86987405e27318266a99053e19680a0bc82239f5c83a2c02e0216330
# Verified Classes:   TransitTTLExpired, RevocationEpochStale, RevocationEpochRegression, BrokeredWarrant, FederationValidator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TransitTTLExpired(RuntimeError):
    """Raised when a brokered warrant's translation is older than its transit_ttl."""
    pass


class RevocationEpochStale(RuntimeError):
    """Raised when the receiver's revocation knowledge is older than the translation it trusts."""
    pass


class RevocationEpochRegression(RuntimeError):
    """Raised when revocation_epoch_ts moves backwards (broker restart / cache eviction)."""
    pass


@dataclass
class BrokeredWarrant:
    scope: str
    not_before: float
    not_after: float
    translated_at: float          # timestamp of the most recent broker translation
    transit_ttl: float            # seconds the translation may be trusted as faithful
    revocation_epoch_ts: float    # source revocation epoch snapshot at translation time


class FederationValidator:
    def __init__(self, epsilon_skew: float = 2.0):
        self.epsilon_skew = epsilon_skew
        self._last_seen_epoch_ts: float = 0.0

    def admit(self, w: BrokeredWarrant, now: float | None = None) -> None:
        now = now if now is not None else time.time()

        # Invariant 1: source lifetime.
        if not (w.not_before - self.epsilon_skew <= now <= w.not_after + self.epsilon_skew):
            raise TransitTTLExpired(
                f"warrant outside source lifetime: now={now} "
                f"window=[{w.not_before},{w.not_after}]"
            )

        # Invariant 2: translation freshness — HARD gate, no fallback to not_after.
        transit_age = now - w.translated_at
        if transit_age > w.transit_ttl + self.epsilon_skew:
            raise TransitTTLExpired(
                f"translation stale: age={transit_age:.1f}s "
                f"ttl={w.transit_ttl}s scope={w.scope}; request re-translation"
            )

        # Invariant 3: revocation epoch must be at least as new as the translation.
        if w.revocation_epoch_ts < w.translated_at - self.epsilon_skew:
            raise RevocationEpochStale(
                f"revocation knowledge older than translation: "
                f"epoch_ts={w.revocation_epoch_ts} translated_at={w.translated_at} "
                f"scope={w.scope}; sync revocations before admitting"
            )

        # Monotonicity: epoch must not regress across admissions.
        if w.revocation_epoch_ts + self.epsilon_skew < self._last_seen_epoch_ts:
            raise RevocationEpochRegression(
                f"revocation epoch regressed: seen={self._last_seen_epoch_ts} "
                f"now={w.revocation_epoch_ts}; possible broker cache eviction"
            )

        self._last_seen_epoch_ts = max(self._last_seen_epoch_ts, w.revocation_epoch_ts)
