# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-revocation-as-authoritative-before-it-has-received-the-revocation-itself.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-revocation-as-authoritative-before-it-has-received-the-revocation-itself.warrant.json
# Markdown SHA-256:   088b0fa55277497e20b4cb03285317446a7b01a081b2141bc9ada38aa2f826a1
# Code AST SHA-256:   3d7ccfaa2224ca1a5cc859a6e9ba2cbea9762d3737d10cdbb8c135411d7b8759
# Verified Classes:   UnprovableLivenessError, Credential, FeedState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnprovableLivenessError(RuntimeError):
    """Raised when a relying party cannot prove a foreign credential is live
    and therefore cannot safely fail-open on an unobserved revocation."""
    pass


@dataclass
class Credential:
    issuer: str
    jti: str
    heartbeat_epoch: Optional[int]  # None => long-lived, no liveness binding


@dataclass
class FeedState:
    issuer: str
    watermark_epoch: Optional[int]  # None => feed partitioned / unknown
    propagation_slo_epochs: int


def evaluate_foreign_credential(
    cred: Credential,
    feed: FeedState,
    now_epoch: int,
    clock_skew_epochs: int = 2,
) -> str:
    if feed.issuer != cred.issuer:
        raise UnprovableLivenessError(
            f"feed issuer {feed.issuer!r} does not match credential issuer {cred.issuer!r}"
        )

    if feed.watermark_epoch is None:
        # Partitioned feed: cannot distinguish "quiet" from "stale".
        return "unverified-liveness:revalidate"

    watermark_age = now_epoch - feed.watermark_epoch
    feed_stale = watermark_age > feed.propagation_slo_epochs

    if cred.heartbeat_epoch is not None:
        heartbeat_fresh = (now_epoch - cred.heartbeat_epoch) <= clock_skew_epochs
        if not heartbeat_fresh:
            # Absence of a fresh heartbeat is revocation-equivalent.
            return "deny:heartbeat-absent"
        return "admit" if not feed_stale else "admit:short-ttl"

    if feed_stale:
        raise UnprovableLivenessError(
            f"issuer {cred.issuer!r} watermark age {watermark_age} exceeds SLO "
            f"{feed.propagation_slo_epochs}; long-lived credential has no liveness "
            f"binding and feed cannot be trusted"
        )

    return "admit:unverified-liveness"


def admit_or_raise(cred: Credential, feed: FeedState, now_epoch: int) -> bool:
    decision = evaluate_foreign_credential(cred, feed, now_epoch)
    if decision.startswith("deny"):
        return False
    if decision.startswith("unverified-liveness"):
        raise UnprovableLivenessError(
            f"credential {cred.jti} from {cred.issuer} cannot be admitted or denied "
            f"without re-validation"
        )
    return True
