# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-document-trust-anchor-during-a-cross-org-verifiable-presentation-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-document-trust-anchor-during-a-cross-org-verifiable-presentation-handshake.warrant.json
# Markdown SHA-256:   b207f2712b1c0236928364243a6ce72191ed5408954fa1cf0515cc156cf2082b
# Code AST SHA-256:   c7a3494faf06a3491c1aa2c2089ff3048b3130442030daa0c5a46a76336e7b1e
# Verified Classes:   StaleTrustAnchorError, VerificationMethod, DidDocumentVersion, VerifiablePresentation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class StaleTrustAnchorError(RuntimeError):
    """Raised when a VP's signing key cannot be proven authorized at the
    presentation's creation instant against the resolved DID document version."""
    pass


@dataclass
class VerificationMethod:
    vm_id: str
    authorized_from: float
    revoked_at: Optional[float] = None  # None => still authorized


@dataclass
class DidDocumentVersion:
    did: str
    version: int
    published_at: float
    methods: dict = field(default_factory=dict)


@dataclass
class VerifiablePresentation:
    did: str
    vm_id: str
    created: float
    signature_valid: bool


def verify_presentation(
    vp: VerifiablePresentation,
    current: DidDocumentVersion,
    history: list[DidDocumentVersion],
    realtime_window_eps: float,
    t_resolve: float,
) -> bool:
    if not vp.signature_valid:
        raise StaleTrustAnchorError(
            f"signature invalid for {vp.vm_id} on {vp.did}"
        )

    current_vm = current.methods.get(vp.vm_id)
    if current_vm is not None and current_vm.revoked_at is None:
        # Fast path: key still authorized now.
        return True

    # Key absent or revoked in current doc: must prove historical authorization.
    if not history:
        # No version history: only safe if VP was created after we observed
        # the current document (no unseen rotation possible).
        if vp.created >= t_resolve - realtime_window_eps:
            return True
        raise StaleTrustAnchorError(
            f"no version history for {vp.did}; VP created {vp.created:.0f} "
            f"predates real-time window (t_resolve={t_resolve:.0f}, eps={realtime_window_eps})"
        )

    historical_vm = None
    for version in history:
        candidate = version.methods.get(vp.vm_id)
        if candidate is not None and candidate.authorized_from <= vp.created:
            if candidate.revoked_at is None or candidate.revoked_at > vp.created:
                historical_vm = candidate
                break

    if historical_vm is None:
        raise StaleTrustAnchorError(
            f"cannot prove {vp.vm_id} authorized at t_c={vp.created:.0f} for {vp.did}"
        )

    if historical_vm.revoked_at is not None and historical_vm.revoked_at <= vp.created:
        raise StaleTrustAnchorError(
            f"{vp.vm_id} revoked at {historical_vm.revoked_at:.0f} "
            f"<= presentation created {vp.created:.0f}"
        )

    return True


def _demo() -> None:
    now = time.time()
    current = DidDocumentVersion(
        did="did:web:agents.a.example:fulfillment-07",
        version=2,
        published_at=now - 120,
        methods={
            "key-2": VerificationMethod("key-2", authorized_from=now - 86400, revoked_at=now - 120),
            "key-3": VerificationMethod("key-3", authorized_from=now - 120),
        },
    )
    history = [
        DidDocumentVersion(
            did=current.did,
            version=1,
            published_at=now - 86400,
            methods={"key-2": VerificationMethod("key-2", authorized_from=now - 86400)},
        ),
        current,
    ]

    stale_vp = VerifiablePresentation(
        did=current.did, vm_id="key-2", created=now - 60, signature_valid=True
    )
    # Created after revocation => must fail closed.
    try:
        verify_presentation(stale_vp, current, history, realtime_window_eps=30, t_resolve=now)
    except StaleTrustAnchorError as exc:
        print("rejected as expected:", exc)
    else:
        raise StaleTrustAnchorError("verifier accepted a post-revocation signature")

    historical_vp = VerifiablePresentation(
        did=current.did, vm_id="key-2", created=now - 300, signature_valid=True
    )
    assert verify_presentation(historical_vp, current, history, 30, now) is True


if __name__ == "__main__":
    _demo()
