# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-outliving-the-did-binding-they-were-minted-against.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-outliving-the-did-binding-they-were-minted-against.warrant.json
# Markdown SHA-256:   cd1468b46c39ef6f0face4401f894069c4ba4303401a85116c36ef456018a2fd
# Code AST SHA-256:   425059e1320c1d81f0c1aef96b06e26fcf180a60aa4faef1345b9e7c75f19911
# Verified Classes:   BindingStaleError, VerificationMethod, DidDocument, DelegationToken
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime, timedelta


class BindingStaleError(RuntimeError):
    """Raised when a delegation token's asserted DID binding is no longer current."""


@dataclass(frozen=True)
class VerificationMethod:
    kid: str
    key_material: str
    active: bool
    relationships: frozenset


@dataclass(frozen=True)
class DidDocument:
    did: str
    version: int
    valid_until: datetime
    methods: dict  # kid -> VerificationMethod


@dataclass(frozen=True)
class DelegationToken:
    delegator_did: str
    subject_did: str
    kid: str
    scope: str
    did_doc_version: int
    exp: datetime
    signature: str


def _signature_ok(token: DelegationToken, method: VerificationMethod) -> bool:
    expected = hashlib.sha256(
        f"{token.delegator_did}|{token.subject_did}|{token.kid}|{token.scope}".encode()
    ).hexdigest()
    return token.signature == expected


def verify_delegation(
    token: DelegationToken,
    fresh_doc: DidDocument,
    now: datetime,
    registry_reachable: bool,
    rotation_window: timedelta,
    last_resolution: datetime,
) -> None:
    if token.exp <= now:
        raise BindingStaleError(f"token expired at {token.exp.isoformat()}")

    if not registry_reachable:
        # Fail closed once the token outlives the safe horizon.
        if now > last_resolution + rotation_window:
            raise BindingStaleError(
                "registry unreachable and token exceeds safe horizon; "
                "cannot confirm delegator binding"
            )
        return

    if fresh_doc.did != token.delegator_did:
        raise BindingStaleError(
            f"resolved document for {fresh_doc.did} does not match token delegator "
            f"{token.delegator_did}"
        )

    # Per-kid check: the named verification method must exist AND be active.
    method = fresh_doc.methods.get(token.kid)
    if method is None:
        raise BindingStaleError(
            f"verification method {token.kid} absent from current document "
            f"version {fresh_doc.version}"
        )
    if not method.active:
        raise BindingStaleError(
            f"verification method {token.kid} deactivated in document "
            f"version {fresh_doc.version}; token minted at version "
            f"{token.did_doc_version} is stale"
        )
    if "capabilityInvocation" not in method.relationships:
        raise BindingStaleError(
            f"verification method {token.kid} lacks capabilityInvocation relationship"
        )
    if not _signature_ok(token, method):
        raise BindingStaleError(
            f"signature does not verify against current key for {token.kid}"
        )


def execute_step_with_epoch(
    token: DelegationToken,
    fresh_doc: DidDocument,
    step_id: str,
    completed_steps: list,
    now: datetime,
    registry_reachable: bool,
    rotation_window: timedelta,
    last_resolution: datetime,
) -> list:
    try:
        verify_delegation(
            token, fresh_doc, now, registry_reachable, rotation_window, last_resolution
        )
    except BindingStaleError:
        # Roll back to the last step whose delegation epoch is still valid.
        raise BindingStaleError(
            f"authority changed mid-task at step {step_id}; "
            f"{len(completed_steps)} prior steps must be rolled back"
        )
    completed_steps.append((step_id, token.did_doc_version, now))
    return completed_steps
