# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-token-whose-did-subject-was-re-keyed-mid-delegation-and-why-signature-validity-alone-cannot-catch-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-capability-token-whose-did-subject-was-re-keyed-mid-delegation-and-why-signature-validity-alone-cannot-catch-i.warrant.json
# Markdown SHA-256:   8c7831dac1c61f4eeb8cf5a8f3fafc5c03a997a3eea6eeac30f9fd42cf6e71b0
# Code AST SHA-256:   672d56e41b657df061094bcd7d54523a8a7cc08831cf895f9e7c0a1f06532e4c
# Verified Classes:   StaleTrustAnchorError, IndeterminateDelegationError, CachedDidDocument
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustAnchorError(RuntimeError):
    """Raised when a cached DID document is too old to authorize a scoped action."""
    pass


class IndeterminateDelegationError(RuntimeError):
    """Raised when a verification key is absent with no revocation record.

    Absence is ambiguous between 'rotated away' and 'never existed'.
    Neither authorizes; neither is retryable.
    """
    pass


@dataclass
class CachedDidDocument:
    did: str
    verification_methods: dict  # key_id -> {"revoked_at": float | None}
    resolved_at: float


FRESHNESS_WINDOW_S = 300.0  # must be < token lifetime and < issuer rotation SLA


def authorize_scoped_call(
    token_key_id: str,
    doc: CachedDidDocument,
    now: float | None = None,
) -> bool:
    now = time.time() if now is None else now

    # Condition 1: never let a cached anchor outlive its freshness window.
    age = now - doc.resolved_at
    if age > FRESHNESS_WINDOW_S:
        raise StaleTrustAnchorError(
            f"cached DID doc for {doc.did} is {age:.0f}s old "
            f"(window {FRESHNESS_WINDOW_S:.0f}s); re-resolve before authorizing"
        )

    # Condition 2/3: key must be present and not revoked at this instant.
    method = doc.verification_methods.get(token_key_id)
    if method is None:
        # Do NOT retry this. A removed key will never reappear.
        raise IndeterminateDelegationError(
            f"key {token_key_id} absent from fresh doc for {doc.did} with no "
            f"revocation record; cannot distinguish rotation from deletion"
        )
    if method["revoked_at"] is not None and method["revoked_at"] <= now:
        # Legitimate revocation: halt the scoped action, do not retry.
        return False

    return True
