# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-did-anchored-agent-passport-whose-verifiable-credential-chain-was-minted-against-a-rotated-issuer-key-silent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-did-anchored-agent-passport-whose-verifiable-credential-chain-was-minted-against-a-rotated-issuer-key-silent.warrant.json
# Markdown SHA-256:   b4120d5dc5129c31a8fcc6dcbcd8eb0b2db13a67f990f0a45678f67a1da3f872
# Code AST SHA-256:   28f0d7b58d8944cbc0def6c1a16cda89b5f5df86d2e47bba02eefc1204e33718
# Verified Classes:   AuthorityContinuityError, KeyRecord, Credential, DidDocument
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime
from typing import Optional


class AuthorityContinuityError(RuntimeError):
    """Raised when a credential's signing key was not continuously authorized
    over the credential's life, or when credential versioning is ambiguous.

    This is an *authority* failure, not an *integrity* failure: the signature
    may validate perfectly. Admission must fail closed regardless.
    """
    pass


@dataclass(frozen=True)
class KeyRecord:
    key_id: str
    authorized_from: datetime
    revoked_at: Optional[datetime]      # None => still authorized
    revocation_reason: Optional[str]    # "scheduled" | "compromise" | None


@dataclass(frozen=True)
class Credential:
    subject_did: str
    issuer_did: str
    signing_key_id: str
    issuance_date: datetime
    credential_version: int
    scope: frozenset[str]


@dataclass(frozen=True)
class DidDocument:
    did: str
    document_version: int
    keys: tuple[KeyRecord, ...]

    def key(self, key_id: str) -> KeyRecord:
        for k in self.keys:
            if k.key_id == key_id:
                return k
        raise AuthorityContinuityError(
            f"signing key {key_id} absent from {self.did} v{self.document_version}"
        )


def verify_passport(
    cred: Credential,
    doc: DidDocument,
    presentation_time: datetime,
    known_latest_version: Optional[int],
    signature_valid: bool,
) -> None:
    """Admit only if signature valid AND signing key continuously authorized
    over [issuance, presentation] AND credential is maximal-version.

    Raises AuthorityContinuityError on any authority/continuity failure.
    """
    if not signature_valid:
        # This is the *easy* failure; integrity, not authority.
        raise AuthorityContinuityError(
            f"signature invalid for {cred.subject_did} under {cred.signing_key_id}"
        )

    if cred.issuer_did != doc.did:
        raise AuthorityContinuityError(
            f"issuer mismatch: cred says {cred.issuer_did}, doc is {doc.did}"
        )

    key = doc.key(cred.signing_key_id)

    # C3: authority interval must CONTAIN the credential's whole life.
    if key.authorized_from > cred.issuance_date:
        raise AuthorityContinuityError(
            f"{key.key_id} not yet authorized at issuance "
            f"({key.authorized_from} > {cred.issuance_date})"
        )

    if key.revoked_at is not None:
        # Compromise rotation: hard cutover, no grace, regardless of timing.
        if key.revocation_reason == "compromise":
            raise AuthorityContinuityError(
                f"{key.key_id} rotated for COMPROMISE; all its credentials void, "
                f"including {cred.subject_did} v{cred.credential_version}"
            )
        # Scheduled rotation: key must still be authorized at presentation,
        # i.e. the credential must not outlive the key's authority.
        if presentation_time >= key.revoked_at:
            raise AuthorityContinuityError(
                f"stale authority: {key.key_id} revoked at {key.revoked_at}, "
                f"presented at {presentation_time}; credential "
                f"{cred.subject_did} v{cred.credential_version} is over-scoped "
                f"relative to current grant"
            )

    # C4: no ambiguous "which grant is current" admission.
    if known_latest_version is not None and cred.credential_version < known_latest_version:
        raise AuthorityContinuityError(
            f"stale credential: {cred.subject_did} presented "
            f"v{cred.credential_version}, latest known v{known_latest_version}; "
            f"refusing to admit narrowed-scope regression"
        )

    # Admitted. Caller MUST persist doc.document_version alongside this decision
    # so replay verifies against pinned state, not live resolution.
    return None
