# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-document-during-agent-to-agent-trust-bootstrapping-when-the-verifier-caches-resolution-state-across-a-credenti.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-document-during-agent-to-agent-trust-bootstrapping-when-the-verifier-caches-resolution-state-across-a-credenti.warrant.json
# Markdown SHA-256:   9bb2afea6f9a19a6db4135fb15f67f48bdb0a78e9399c6224d7333e4b210c8ea
# Code AST SHA-256:   ed5bde9bb93a6f56071c4874187ce2e187de8a5e5f8eaeb9b3dd09e265c12a3a
# Verified Classes:   StaleDIDBindingError, CachedDIDEntry, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleDIDBindingError(RuntimeError):
    """Raised when a verification decision would rest on an unversioned or
    stale DID-document binding. Fail closed to indeterminate; never fall back
    to a cached key when the binding cannot be proven current for the
    credential's issuance window."""


@dataclass(frozen=True)
class CachedDIDEntry:
    did: str
    key_multibase: str
    document_version: Optional[str]      # versionId or document hash
    document_updated: Optional[float]    # epoch seconds of last doc update
    resolved_at: float                   # epoch seconds of resolution
    revoked_at: Optional[float] = None   # revocation time of this key, if any


@dataclass(frozen=True)
class Credential:
    issuer_did: str
    issuance_date: float                 # epoch seconds
    signature_valid_against_key: bool


def re_resolve_required(
    cred: Credential,
    cached: CachedDIDEntry,
    peer_rotation_period: float,
    now: float,
    clock_skew: float = 30.0,
) -> bool:
    if cached.document_version is None or cached.document_updated is None:
        return True  # unversioned entry is never a valid basis
    if cred.issuance_date > cached.document_updated + clock_skew:
        return True  # credential minted after the version we cached
    if cached.revoked_at is not None and cred.issuance_date > cached.revoked_at - clock_skew:
        return True  # key was revoked before/around issuance
    if (now - cached.resolved_at) > peer_rotation_period:
        return True  # declared cadence exceeded
    return False


def verify_credential(
    cred: Credential,
    cached: CachedDIDEntry,
    peer_rotation_period: float,
    resolver_available: bool,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    if re_resolve_required(cred, cached, peer_rotation_period, now):
        if not resolver_available:
            # Cannot prove the binding is current -> indeterminate, fail closed.
            raise StaleDIDBindingError(
                f"cannot verify {cred.issuer_did}: cached document version "
                f"{cached.document_version!r} does not cover issuance_date "
                f"{cred.issuance_date} and resolver is unavailable"
            )
        raise StaleDIDBindingError(
            f"re-resolution required for {cred.issuer_did} before verifying: "
            f"issuance {cred.issuance_date} vs cached updated "
            f"{cached.document_updated}, revoked_at {cached.revoked_at}"
        )

    if not cred.signature_valid_against_key:
        # Do NOT cache this as peer distrust; it may be a cache artifact.
        raise StaleDIDBindingError(
            f"signature check failed for {cred.issuer_did} against version "
            f"{cached.document_version}; treat as indeterminate, not distrust"
        )

    return True
