# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-verifiable-credential-whose-subject-did-resolves-to-a-rotated-keypair-the-aaif-delegation-chain-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-verifiable-credential-whose-subject-did-resolves-to-a-rotated-keypair-the-aaif-delegation-chain-replay.warrant.json
# Markdown SHA-256:   ef88b121bb2afeb4a2a17ecdea9a1941e06bba2cb6998170b218aa1c8906c5ad
# Code AST SHA-256:   bdba6061fa2ed346e0ab4c455776b8636cc980d14109ad476705d5b078133d8d
# Verified Classes:   DelegationLivenessError, ResolvedDID, DelegationEdge, SessionToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class DelegationLivenessError(RuntimeError):
    """Raised when a delegation VC's chain no longer resolves to a live verification method."""


@dataclass(frozen=True)
class ResolvedDID:
    did: str
    verification_methods: FrozenSet[str]   # currently authorized key ids
    revoked: FrozenSet[str]                # key ids explicitly revoked
    resolved_at: float                     # monotonic seconds


@dataclass(frozen=True)
class DelegationEdge:
    issuer_did: str
    subject_did: str
    proof_key_id: str        # e.g. "did:aaif:planner#key-1"
    expires_at: float


@dataclass(frozen=True)
class SessionToken:
    subject_did: str
    chain_thumbprints: FrozenSet[str]   # hash of resolved key set at handshake
    opened_at: float
    ttl: float


def assert_edge_live(edge: DelegationEdge, resolved: ResolvedDID, now: float) -> None:
    """Enforce the AAIF liveness invariant for a single delegation edge at use-time."""
    if edge.proof_key_id in resolved.revoked:
        raise DelegationLivenessError(
            f"replay window: proof key {edge.proof_key_id} is revoked but was used "
            f"against stale resolution of {resolved.did}"
        )
    if edge.proof_key_id not in resolved.verification_methods:
        raise DelegationLivenessError(
            f"proof key {edge.proof_key_id} not currently authorized for {resolved.did}"
        )
    if now >= edge.expires_at:
        raise DelegationLivenessError(
            f"delegation edge {edge.issuer_did}->{edge.subject_did} expired at {edge.expires_at}"
        )


def assert_session_live(
    token: SessionToken,
    fresh_chain_thumbprints: FrozenSet[str],
    now: float,
    chain_min_ttl: float,
) -> None:
    """Re-check session against a fresh resolution; bind session to chain liveness."""
    if now - token.opened_at >= min(token.ttl, chain_min_ttl):
        raise DelegationLivenessError(
            "session exceeded chain liveness bound; re-handshake required"
        )
    if token.chain_thumbprints != fresh_chain_thumbprints:
        raise DelegationLivenessError(
            "session thumbprint set diverged from fresh resolution "
            "(possible key rotation or DID-aliasing replay)"
        )


def verify_use(
    edges: list[DelegationEdge],
    resolve: callable,
    token: Optional[SessionToken],
    now: float,
) -> SessionToken:
    """Resolve-per-use verification satisfying the AAIF liveness invariant."""
    thumbprints: set[str] = set()
    min_ttl = float("inf")
    for edge in edges:
        resolved = resolve(edge.issuer_did)          # MUST be fresh, not cached
        assert_edge_live(edge, resolved, now)
        thumbprints.add(edge.proof_key_id)
        min_ttl = min(min_ttl, edge.expires_at - now)

    fp = frozenset(thumbprints)
    if token is not None:
        assert_session_live(token, fp, now, min_ttl)
        return token
    return SessionToken(
        subject_did=edges[-1].subject_did,
        chain_thumbprints=fp,
        opened_at=now,
        ttl=min_ttl,
    )
