# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-trust-anchor-during-cross-org-verifiable-credential-exchange-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-did-trust-anchor-during-cross-org-verifiable-credential-exchange-mid-task.warrant.json
# Markdown SHA-256:   ab8749f1736a808f95fd8118753801e6291dce1a52cdf5d50edc46a36d4eb00a
# Code AST SHA-256:   bf8e4f5e129025a1d30e3d3034cc07b027ebb93615bfca9a498b6442e2cd8bce
# Verified Classes:   StaleTrustAnchorError, TrustLease, FederatedSigner
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class StaleTrustAnchorError(RuntimeError):
    """Raised when a signing operation is attempted against a trust lease
    whose backing DID anchor is stale, re-scoped, or no longer authorizes
    the signing key. This is a terminal identity-authorization fault and
    MUST NOT be retried with the same key."""
    pass


@dataclass(frozen=True)
class TrustLease:
    peer_did: str
    resolved_document_hash: str
    resolved_at: float
    authorized_vm_ids: frozenset
    credential_valid_until: float


def _hash_document(doc: dict) -> str:
    canonical = repr(sorted(doc.items())).encode()
    return hashlib.sha256(canonical).hexdigest()


class FederatedSigner:
    def __init__(self, anchor_staleness_budget_s: float, resolver):
        self.S = anchor_staleness_budget_s
        self.resolver = resolver  # callable(did) -> dict

    def assert_lease_valid(self, lease: TrustLease, signing_vm_id: str) -> None:
        now = time.time()

        # 1. Lease must not outlive the credential it was derived from.
        if now >= lease.credential_valid_until:
            raise StaleTrustAnchorError(
                f"credential expired at {lease.credential_valid_until}"
            )

        # 2. Anchor staleness budget: re-resolve before trusting.
        if now - lease.resolved_at >= self.S:
            fresh = self.resolver(lease.peer_did)
            fresh_hash = _hash_document(fresh)
            if fresh_hash != lease.resolved_document_hash:
                raise StaleTrustAnchorError(
                    f"DID document for {lease.peer_did} changed since lease "
                    f"(cached {lease.resolved_document_hash[:12]}, "
                    f"fresh {fresh_hash[:12]}); re-derive lease before signing"
                )

        # 3. The signing key must still be authorized for assertionMethod.
        if signing_vm_id not in lease.authorized_vm_ids:
            raise StaleTrustAnchorError(
                f"verification method {signing_vm_id} not authorized under "
                f"current anchor for {lease.peer_did}; key likely re-scoped "
                f"by rotation — do not retry, re-derive lease"
            )

    def sign_attestation(self, lease: TrustLease, signing_vm_id: str,
                         payload: bytes, keystore) -> bytes:
        self.assert_lease_valid(lease, signing_vm_id)
        return keystore.sign(signing_vm_id, payload)


# --- retry policy discipline ---------------------------------------------

RETRYABLE = {"network-timeout", "registry-unavailable", "rate-limited"}
TERMINAL_IDENTITY = {"proof-purpose-mismatch", "anchor-stale",
                     "key-not-authorized"}


def classify_and_dispatch(err: Exception, attempt: int, max_attempts: int):
    code = getattr(err, "code", None)
    if code in TERMINAL_IDENTITY:
        # Invalidate lease, force re-resolution, escalate — never retry.
        raise StaleTrustAnchorError(
            f"terminal identity fault '{code}' at attempt {attempt}; "
            f"lease invalidated, escalate to federation supervisor"
        ) from err
    if code in RETRYABLE and attempt < max_attempts:
        return "retry"
    raise err
