# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-verifiable-credential-whose-issuer-s-trust-registry-entry-was-valid-at-attestation-time-but.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-verifiable-credential-whose-issuer-s-trust-registry-entry-was-valid-at-attestation-time-but.warrant.json
# Markdown SHA-256:   4e1b2d8988495537cbba8b536d4e5fba6b4cfb19dc97b9effe9cc0c58a0adc61
# Code AST SHA-256:   e1a16f58beaceb431b842850f9608af30287b220ef8211ab03504ba6d446d6fc
# Verified Classes:   StaleTrustBindingError, IssuerRevokedMidHandoffError, RegistryResolution, VerifiableCredential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleTrustBindingError(RuntimeError):
    """Raised when a federated registry resolution cannot establish current trust."""


class IssuerRevokedMidHandoffError(RuntimeError):
    """Raised when the issuer's authoritative epoch advanced past the credential's issuance epoch."""


@dataclass(frozen=True)
class RegistryResolution:
    issuer_id: str
    revocation_epoch: int
    as_of_unix: float
    authoritative: bool


@dataclass(frozen=True)
class VerifiableCredential:
    issuer_id: str
    issuance_epoch: int
    valid_until_unix: float
    signature_valid: bool


MAX_STALENESS_SECONDS = 30.0


def validate_federated_credential(
    vc: VerifiableCredential,
    replica: Optional[RegistryResolution],
    authoritative: Optional[RegistryResolution],
    now_unix: float,
) -> bool:
    if not vc.signature_valid:
        raise StaleTrustBindingError(f"signature invalid for issuer {vc.issuer_id}")
    if now_unix >= vc.valid_until_unix:
        raise StaleTrustBindingError(f"credential expired for issuer {vc.issuer_id}")

    # Prefer authoritative; fall back to replica only within staleness bound.
    binding = authoritative if authoritative is not None else replica
    if binding is None:
        raise StaleTrustBindingError(
            f"no registry binding resolvable for issuer {vc.issuer_id}"
        )

    staleness = now_unix - binding.as_of_unix
    if not binding.authoritative and staleness > MAX_STALENESS_SECONDS:
        # The trap: replica answered, signature valid, but we cannot date the trust.
        raise StaleTrustBindingError(
            f"replica binding for {vc.issuer_id} stale by {staleness:.1f}s "
            f"(bound {MAX_STALENESS_SECONDS}s); refuse to accept undated trust"
        )

    if binding.revocation_epoch > vc.issuance_epoch:
        raise IssuerRevokedMidHandoffError(
            f"issuer {vc.issuer_id} epoch advanced {vc.issuance_epoch}->"
            f"{binding.revocation_epoch} after credential issuance; "
            f"revoked mid-handoff"
        )

    return True


def attempt_handoff(vc, replica, authoritative, now_unix) -> str:
    try:
        validate_federated_credential(vc, replica, authoritative, now_unix)
    except StaleTrustBindingError as e:
        return f"HANDOFF_BLOCKED_UNVERIFIABLE: {e}"
    except IssuerRevokedMidHandoffError as e:
        return f"HANDOFF_REJECTED: {e}"
    return "HANDOFF_ACCEPTED"
