# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-warrant-after-a-peer-s-credential-rotation-and-why-a-valid-aaif-proof-chain-is-not-sufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-warrant-after-a-peer-s-credential-rotation-and-why-a-valid-aaif-proof-chain-is-not-sufficient.warrant.json
# Markdown SHA-256:   5fa642fce61c196ae7c6da8040d358776ad3f89e053a99f64da4272c3c29f937
# Code AST SHA-256:   9047f14255a78d1f75f11bc12608efd3b1bda8a863c9b511ada1accab3fe8fed
# Verified Classes:   DisownedDelegationError, Hop, IssuerState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class DisownedDelegationError(RuntimeError):
    """Raised when a hop's signing key is absent from the issuer's current key set."""


@dataclass(frozen=True)
class Hop:
    issuer_id: str
    signing_key_id: str
    key_epoch: int          # epoch recorded at proof issuance
    scope: frozenset


@dataclass(frozen=True)
class IssuerState:
    current_key_ids: frozenset
    current_epoch: int
    revoked_key_ids: frozenset


def rederive_delegation(
    chain: list[Hop],
    live_state: Mapping[str, IssuerState],
) -> None:
    """
    Re-derive federated authority for a multi-hop AAIF chain against live
    issuer key state. Cryptographic validity is assumed already checked;
    this enforces the continuity invariant: every hop's signing key must
    still be present in the issuer's *current* key set.
    """
    if len(chain) < 2:
        # Single-hop: issuer is the root principal; key-state check is
        # sufficient and the disownment failure mode does not arise.
        return

    for hop in chain:
        state = live_state.get(hop.issuer_id)
        if state is None:
            raise DisownedDelegationError(
                f"no live state for issuer {hop.issuer_id!r}; cannot confirm authority"
            )
        if hop.signing_key_id in state.revoked_key_ids:
            raise DisownedDelegationError(
                f"hop signed by revoked key {hop.signing_key_id!r} "
                f"of issuer {hop.issuer_id!r}"
            )
        if hop.signing_key_id not in state.current_key_ids:
            raise DisownedDelegationError(
                f"hop signed by key {hop.signing_key_id!r} absent from "
                f"current key set of issuer {hop.issuer_id!r} "
                f"(epoch {hop.key_epoch} -> {state.current_epoch}); "
                f"delegation disowned"
            )
