# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-did-document-key-rotation-lag-before-validating-a-cross-org-aaif-verifiable-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-did-document-key-rotation-lag-before-validating-a-cross-org-aaif-verifiable-credential.warrant.json
# Markdown SHA-256:   22a6fe97687b582d4df988242def022e7fe378f9ac5873eb021beff12bfc4b80
# Code AST SHA-256:   85c88924a3267e927ff85c106459c712c6ae897223743397b8d01e1543a6e80d
# Verified Classes:   RotationLagFault, DidDocument, VerifiableCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RotationLagFault(RuntimeError):
    """Raised when a credential's signing key cannot be confirmed current
    against a freshly resolved DID document."""
    pass


@dataclass
class DidDocument:
    key_ids: set[str]
    cached_at: float          # epoch seconds when this doc was retrieved
    version: int


@dataclass
class VerifiableCredential:
    issuer_did: str
    signing_key_id: str
    issuance_time: float
    expires_at: float


def validate_cross_org_vc(
    vc: VerifiableCredential,
    cached_doc: DidDocument,
    resolve_fresh,                 # callable(did) -> DidDocument
    now: float | None = None,
    rotation_grace_window: float = 300.0,
) -> bool:
    now = time.time() if now is None else now

    if now >= vc.expires_at:
        return False

    # Case 1: cache postdates issuance -> cache is authoritative.
    if cached_doc.cached_at >= vc.issuance_time:
        if vc.signing_key_id not in cached_doc.key_ids:
            return False
        return True

    # Case 2: cache predates issuance -> ambiguous, must resolve fresh.
    age = now - cached_doc.cached_at
    if age > rotation_grace_window:
        # Stale beyond grace: cannot trust cache at all.
        try:
            fresh = resolve_fresh(vc.issuer_did)
        except Exception as exc:
            raise RotationLagFault(
                f"resolver unavailable for {vc.issuer_did}; "
                f"cannot confirm key currency"
            ) from exc
        if vc.signing_key_id not in fresh.key_ids:
            raise RotationLagFault(
                f"signing key {vc.signing_key_id} absent from fresh DID doc "
                f"v{fresh.version} for {vc.issuer_did}; key retired before "
                f"credential issuance window"
            )
        return True

    # Within grace window but cache older than issuance: force fresh check.
    try:
        fresh = resolve_fresh(vc.issuer_did)
    except Exception as exc:
        raise RotationLagFault(
            f"resolver unavailable for {vc.issuer_did} inside grace window; "
            f"fail closed"
        ) from exc

    if vc.signing_key_id not in fresh.key_ids:
        raise RotationLagFault(
            f"rotation lag: {vc.signing_key_id} retired in DID doc "
            f"v{fresh.version} but cached v{cached_doc.version} still "
            f"authoritative; reject"
        )
    return True
