# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-agent-credential-when-the-trust-anchor-s-did-document-has-rotated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-agent-credential-when-the-trust-anchor-s-did-document-has-rotated-mid-handoff.warrant.json
# Markdown SHA-256:   40cb462b3ab50fc647e43bcf3c93f8a61a0f0d91c2d75104e3d30ce1a8455771
# Code AST SHA-256:   3b69097a1df4ff179ac625da73e008f36d60bd61f8b57b2833825d2aece1d407
# Verified Classes:   AnchorIndeterminateError, Verdict, DIDDocument, DelegatedCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class AnchorIndeterminateError(RuntimeError):
    """Raised when the issuance-time trust anchor cannot be established.

    This is deliberately NOT a proof-invalidity signal. Callers MUST
    treat it as a pause-and-recheck condition, preserving task state,
    rather than as a revocation of the delegation.
    """
    pass


class Verdict(Enum):
    VALID = "valid"
    PROOF_INVALID = "proof_invalid"
    ANCHOR_INDETERMINATE = "anchor_indeterminate"
    AUTHORITY_REVOKED = "authority_revoked"


@dataclass
class DIDDocument:
    version_time: float
    verification_methods: set[str]
    # successor chain proving benign rotation vs. compromise removal
    prior_key_chain: dict[str, str] = field(default_factory=dict)
    revoked_for_compromise: set[str] = field(default_factory=set)


@dataclass
class DelegatedCredential:
    issuer_did: str
    key_id: str            # e.g. "#key-1"
    iat: float
    exp: float
    signature_ok: bool


def verify_delegated_credential(
    cred: DelegatedCredential,
    resolve_current,             # () -> DIDDocument
    resolve_at_issuance,         # (t: float) -> Optional[DIDDocument]
    is_revoked,                  # (cred) -> bool
    now: Optional[float] = None,
) -> Verdict:
    now = now if now is not None else time.time()

    if now > cred.exp:
        return Verdict.PROOF_INVALID
    if not cred.signature_ok:
        return Verdict.PROOF_INVALID

    # 1. Current-authority check: is the issuer still authorized now?
    current = resolve_current()
    if is_revoked(cred):
        return Verdict.AUTHORITY_REVOKED

    # 2. Issuance-time anchor: the document authoritative at cred.iat.
    issuance_doc = resolve_at_issuance(cred.iat)
    if issuance_doc is None:
        # We cannot establish which anchor the proof was made against.
        # Do NOT call this invalid; the delegation may be perfectly sound.
        raise AnchorIndeterminateError(
            f"cannot resolve {cred.issuer_did} at iat={cred.iat}; "
            f"current doc version_time={current.version_time}. "
            f"Pause and re-resolve via transparency log; preserve task state."
        )

    key_present_at_issuance = cred.key_id in issuance_doc.verification_methods
    if not key_present_at_issuance:
        # The key was never valid when the credential was issued.
        return Verdict.PROOF_INVALID

    # 3. Anchor continuity: if the key is gone now, was the removal benign?
    if cred.key_id not in current.verification_methods:
        if cred.key_id in current.revoked_for_compromise:
            return Verdict.AUTHORITY_REVOKED
        successor = current.prior_key_chain.get(cred.key_id)
        if successor is None:
            # Key vanished with no successor chain: treat as indeterminate,
            # not invalid — the rotation may be mid-propagation.
            raise AnchorIndeterminateError(
                f"{cred.key_id} absent from current doc with no successor "
                f"chain; rotation may be in flight. Re-resolve before aborting."
            )
        # Benign rotation: credential was valid at issuance, issuer
        # rotated forward. Accept under point-in-time semantics.
        return Verdict.VALID

    return Verdict.VALID


def handoff_with_anchor_recovery(cred, resolve_current, resolve_at_issuance,
                                 is_revoked, checkpoint, max_retries=3):
    last_err = None
    for attempt in range(max_retries):
        try:
            return verify_delegated_credential(
                cred, resolve_current, resolve_at_issuance, is_revoked
            )
        except AnchorIndeterminateError as e:
            last_err = e
            # Preserve accumulated state; this is a pause, not a revocation.
            checkpoint.save(reason="anchor_indeterminate", attempt=attempt)
            time.sleep(0.5 * (attempt + 1))
    raise AnchorIndeterminateError(
        f"anchor still indeterminate after {max_retries} attempts: {last_err}"
    )
