# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-agent-warrant-when-its-did-document-has-rotated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-agent-warrant-when-its-did-document-has-rotated-mid-handoff.warrant.json
# Markdown SHA-256:   7f143a9330ba2572dc9b560fd24da6e021bc1dca22d545ee7348d6bb64e9cb10
# Code AST SHA-256:   0578db8d6ae29f6d8c78d45a33b6d09b2b6a50bdb4bad007bb146ed72b35b74a
# Verified Classes:   DIDBindingUnreconstructable, DIDDocumentVersion, CapabilityVC
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DIDBindingUnreconstructable(RuntimeError):
    """Raised when a verifier cannot prove which DID document version was
    authoritative at the credential's issuance instant, so the warrant's
    binding to an identity cannot be established."""
    pass


@dataclass
class DIDDocumentVersion:
    version_id: str
    key_fragment: str
    public_key: bytes
    created: float
    deactivated: float | None
    sequence: int


@dataclass
class CapabilityVC:
    issuer_did: str
    subject_did: str
    verification_method: str      # e.g. "did:web:planner.a.example#key-1"
    issuance_date: float
    signature: bytes


def verify_federated_warrant(
    vc: CapabilityVC,
    resolve_versions,             # callable(did) -> list[DIDDocumentVersion]
    cached_doc: DIDDocumentVersion | None,
    cache_ttl: float,
    last_seen_sequence: int,
    now: float | None = None,
) -> DIDDocumentVersion:
    now = now if now is not None else time.time()

    versions = resolve_versions(vc.issuer_did)
    if not versions:
        raise DIDBindingUnreconstructable(
            f"no DID document versions resolvable for {vc.issuer_did}"
        )

    # Enforce monotonic sequence: a lower sequence than previously observed
    # is a rollback signal, not a cache miss.
    max_seq = max(v.sequence for v in versions)
    if max_seq < last_seen_sequence:
        raise DIDBindingUnreconstructable(
            f"DID document rollback for {vc.issuer_did}: "
            f"observed seq {max_seq} < last seen {last_seen_sequence}"
        )

    # Rotation-window check: if issuance is within one cache TTL of the
    # latest document update, the cached view cannot be trusted.
    latest = max(versions, key=lambda v: v.sequence)
    rotation_proximate = (latest.created - vc.issuance_date) < cache_ttl

    if cached_doc is not None and not rotation_proximate:
        # Cache is safe only if it predates no rotation relevant to issuance.
        if cached_doc.created <= vc.issuance_date and (
            cached_doc.deactivated is None or cached_doc.deactivated > vc.issuance_date
        ):
            return cached_doc

    # Pin the version whose validity window contains the issuance instant.
    fragment = vc.verification_method.split("#", 1)[-1]
    candidates = [
        v for v in versions
        if v.key_fragment == fragment
        and v.created <= vc.issuance_date
        and (v.deactivated is None or v.deactivated > vc.issuance_date)
    ]
    if not candidates:
        raise DIDBindingUnreconstructable(
            f"cannot reconstruct DID document version for {vc.issuer_did} "
            f"at issuance {vc.issuance_date}: no version of #{fragment} "
            f"was authoritative then (rotation window unrecoverable)"
        )

    pinned = max(candidates, key=lambda v: v.created)
    if pinned.sequence < last_seen_sequence:
        raise DIDBindingUnreconstructable(
            f"pinned version seq {pinned.sequence} precedes last seen "
            f"{last_seen_sequence} for {vc.issuer_did}"
        )
    return pinned
