# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-did-resolved-agent-passport-when-the-issuer-s-key-rotation-window-straddles-the-credential-s-proof-timestamp.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-did-resolved-agent-passport-when-the-issuer-s-key-rotation-window-straddles-the-credential-s-proof-timestamp.warrant.json
# Markdown SHA-256:   bab8fa5f20dea2aae88e6976a1f181b914dd0a02ed9fbaf191dd8e2db36e02ca
# Code AST SHA-256:   1936ff002bd4cbf4c2daaa4526a09e33d20812d46a0f7087d6e55f96a61a9c5e
# Verified Classes:   PassportTrustAnchorError, KeyState, DidDocument, Passport
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class PassportTrustAnchorError(RuntimeError):
    """Raised when DID-resolved passport validation hits an unresolvable
    temporal/rotation boundary and cannot safely accept or reject."""
    pass


@dataclass
class KeyState:
    kid: str
    valid_from: float          # epoch seconds
    valid_until: Optional[float]  # None = still current
    revocation_reason: Optional[str] = None  # e.g. "keyCompromise", "superseded"


@dataclass
class DidDocument:
    did: str
    updated: float             # versionTime of this resolution
    keys: list[KeyState] = field(default_factory=list)


@dataclass
class Passport:
    subject_did: str
    signing_kid: str
    proof_created: float       # t_proof
    signature_valid: bool


CLOCK_SKEW = 120.0             # delta, seconds
MIN_ROTATION_INTERVAL = 3600.0 # shortest allowed key lifetime


def validate_passport(
    passport: Passport,
    doc: DidDocument,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now
    t_proof = passport.proof_created

    # Guard 1: resolution trust — doc must not be stale relative to the proof,
    # and must not claim to be newer than our own clock.
    if doc.updated < t_proof - CLOCK_SKEW:
        raise PassportTrustAnchorError(
            f"DID doc {doc.did} updated={doc.updated} predates proof "
            f"{t_proof}; stale resolution, possible replay."
        )
    if doc.updated > now + CLOCK_SKEW:
        raise PassportTrustAnchorError(
            f"DID doc {doc.did} updated={doc.updated} is in the future "
            f"vs now={now}; untrustworthy resolution."
        )

    # Guard 2: provenance must exist to compute the rotation boundary.
    if not doc.keys:
        raise PassportTrustAnchorError(
            f"DID doc {doc.did} carries no key history; rotation "
            f"boundary is uncomputable — deny-with-audit."
        )

    # Guard 3: skew budget must be smaller than the shortest rotation interval,
    # else a skewed peer can dress a post-rotation proof as pre-rotation.
    intervals = [
        (k.valid_until - k.valid_from)
        for k in doc.keys
        if k.valid_until is not None
    ]
    if intervals and CLOCK_SKEW >= min(intervals):
        raise PassportTrustAnchorError(
            f"CLOCK_SKEW={CLOCK_SKEW}s >= min rotation interval "
            f"{min(intervals)}s; skew can straddle the rotation boundary."
        )

    if not passport.signature_valid:
        return False

    # Guard 4: the actual invariant — t_proof must fall inside the signing
    # key's authorized interval, and that key must not be compromise-revoked.
    for k in doc.keys:
        if k.kid != passport.signing_kid:
            continue
        if k.revocation_reason == "keyCompromise":
            raise PassportTrustAnchorError(
                f"Signing key {k.kid} revoked for keyCompromise; "
                f"passport must be rejected regardless of t_proof."
            )
        lo = k.valid_from
        hi = k.valid_until if k.valid_until is not None else float("inf")
        if lo <= t_proof + CLOCK_SKEW < hi:
            return True
        return False  # key known but proof outside its interval

    # Signing key not present in any state of the resolved doc.
    raise PassportTrustAnchorError(
        f"Signing kid {passport.signing_kid} absent from {doc.did} history; "
        f"cannot establish rotation boundary."
    )
