# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-agent-manifest-whose-did-document-has-rotated-keys-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-agent-manifest-whose-did-document-has-rotated-keys-mid-handshake.warrant.json
# Markdown SHA-256:   649b639d56e4fb3dcc2eaeebee80dfc59226e95b39e034de2027d6c24d245115
# Code AST SHA-256:   d5dcc49fe12f92c54bf742d5154b403a72ce328fd414f93a08ac7b0ee5813d12
# Verified Classes:   ManifestTrustError, VerificationMethod, DidDocument, SignedManifest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ManifestTrustError(RuntimeError):
    """Raised when a signed agent manifest cannot be bound to an authoritative DID key at its signing instant."""
    pass


@dataclass
class VerificationMethod:
    key_id: str
    created: float
    revocation_time: Optional[float]  # None => not revoked


@dataclass
class DidDocument:
    did: str
    updated: float
    methods: dict  # key_id -> VerificationMethod


@dataclass
class SignedManifest:
    issuer_did: str
    signed_at: float          # when the JWS was produced (distinct from iat)
    exp: float
    signing_key_id: str


def verify_manifest_trust(
    manifest: SignedManifest,
    cached_doc: DidDocument,
    resolver,                 # callable(did) -> DidDocument | None
    now: float,
) -> DidDocument:
    if manifest.issuer_did != cached_doc.did:
        raise ManifestTrustError(
            f"manifest issuer {manifest.issuer_did} does not match resolved doc {cached_doc.did}"
        )

    # Invariant: the DID document must be at least as new as the signing instant.
    # A document older than signed_at cannot reflect a rotation that happened after signing.
    if cached_doc.updated < manifest.signed_at:
        fresh = resolver(manifest.issuer_did)
        if fresh is None:
            # Fail closed: the stale document is exactly the one that cannot answer the question.
            raise ManifestTrustError(
                f"cannot prove key authority for {manifest.signing_key_id} at signed_at="
                f"{manifest.signed_at}: cached doc updated={cached_doc.updated}, resolver unavailable"
            )
        if fresh.updated < manifest.signed_at:
            raise ManifestTrustError(
                f"resolver returned doc updated={fresh.updated} still older than signed_at={manifest.signed_at}"
            )
        cached_doc = fresh

    method = cached_doc.methods.get(manifest.signing_key_id)
    if method is None:
        raise ManifestTrustError(
            f"verification method {manifest.signing_key_id} absent from authoritative doc "
            f"(updated={cached_doc.updated})"
        )

    # Temporal binding: the key must have been authoritative at the signing instant.
    if manifest.signed_at < method.created:
        raise ManifestTrustError(
            f"manifest signed_at={manifest.signed_at} precedes key creation {method.created} "
            f"for {method.key_id}"
        )

    if method.revocation_time is not None and manifest.signed_at >= method.revocation_time:
        raise ManifestTrustError(
            f"manifest signed_at={manifest.signed_at} at/after revocation {method.revocation_time} "
            f"for {method.key_id}: revoked key cannot attest manifest"
        )

    if now >= manifest.exp:
        raise ManifestTrustError(
            f"manifest expired at {manifest.exp}, now={now}"
        )

    return cached_doc
