# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-federation-is-replaying-a-stale-trust-anchor-during-cross-org-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-credential-federation-is-replaying-a-stale-trust-anchor-during-cross-org-agent-handoff.warrant.json
# Markdown SHA-256:   4c4787bd43958f6dc2870eb308e3fd58511fd613728c62599176f2c4faa29de2
# Code AST SHA-256:   6a0dbd7d64e7b1bbba951e3da309e49645cf26c60dec4c81f647393404a8be01
# Verified Classes:   StaleTrustAnchorError, AnchorSnapshot, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustAnchorError(RuntimeError):
    """Raised when a credential is verified against an anchor/revocation snapshot
    that predates the credential's own issuance or status reference."""
    pass


@dataclass(frozen=True)
class AnchorSnapshot:
    updated: float            # epoch seconds, from DID doc / registry 'updated'
    revocation_version: int   # from the cached revocation list


@dataclass(frozen=True)
class Credential:
    issuance_date: float      # epoch seconds
    status_version: int       # from credentialStatus
    issuer_key_id: str


CLOCK_SKEW_ALLOWANCE = 300.0  # seconds; subtract before comparing


def assert_anchor_fresh_enough(snapshot: AnchorSnapshot, cred: Credential) -> None:
    """Hard precondition: refuse to verify if the snapshot is provably older
    than the artifact it is judging. This is checkable offline."""
    if snapshot.updated + CLOCK_SKEW_ALLOWANCE < cred.issuance_date:
        raise StaleTrustAnchorError(
            f"anchor updated at {snapshot.updated} precedes credential "
            f"issuance {cred.issuance_date} beyond skew allowance "
            f"({CLOCK_SKEW_ALLOWANCE}s); refusing verification of "
            f"credential signed by {cred.issuer_key_id}"
        )
    if snapshot.revocation_version < cred.status_version:
        raise StaleTrustAnchorError(
            f"cached revocation version {snapshot.revocation_version} is older "
            f"than credential status reference {cred.status_version}; "
            f"revocation state is structurally stale"
        )


def verify_handoff(snapshot: AnchorSnapshot, cred: Credential,
                   signature_valid: bool) -> bool:
    # Freshness gate runs BEFORE signature acceptance, so a mathematically
    # valid signature against a stale anchor cannot short-circuit the check.
    assert_anchor_fresh_enough(snapshot, cred)
    if not signature_valid:
        raise StaleTrustAnchorError(
            f"signature invalid for key {cred.issuer_key_id} under fresh anchor"
        )
    return True
