# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-issuer-chain-re-anchors-to-a-rotated-root-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-issuer-chain-re-anchors-to-a-rotated-root-mid-delegation.warrant.json
# Markdown SHA-256:   169d51680f16e612e6e57f454b2bf4b3a95eba94df6cd53434ab29b823548c4a
# Code AST SHA-256:   357a7d185b5008d269899703a4a4c9fd88d421bce916bed3cb5138228f9c4aa2
# Verified Classes:   AnchorStaleDelegationError, Hop, RotationProof
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AnchorStaleDelegationError(RuntimeError):
    """Raised when a delegated AAIF chain is cryptographically intact but
    its intermediate issuer is superseded in the current registry epoch
    with no bridging rotation proof covering presentation time."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str
    subject: str
    signed_under_root: str      # root key hash the signature verifies against
    revoked_in_epoch: Optional[int] = None


@dataclass(frozen=True)
class RotationProof:
    issuer: str
    from_root: str
    to_root: str
    surviving_delegations: frozenset  # hashes of delegations that survive
    valid_from: int
    valid_to: int


def verify_delegated_chain(
    chain: list[Hop],
    current_epoch: int,
    current_root: str,
    rotation_proofs: list[RotationProof],
    presentation_time: int,
    pinned_epoch: Optional[int] = None,
) -> None:
    # Fail-closed on epoch ambiguity: the verifier must know which epoch it
    # is judging against, and must not let the presenter pick via hints.
    if pinned_epoch is not None and pinned_epoch != current_epoch:
        raise AnchorStaleDelegationError(
            f"chain pinned to epoch {pinned_epoch} but registry is at "
            f"{current_epoch}; refusing cross-epoch trust without bridge"
        )

    for hop in chain:
        # Revocation in the current epoch is fatal regardless of signature.
        if hop.revoked_in_epoch is not None and hop.revoked_in_epoch <= current_epoch:
            raise AnchorStaleDelegationError(
                f"issuer {hop.issuer} revoked in epoch "
                f"{hop.revoked_in_epoch} <= {current_epoch}"
            )

        # Anchor-consistency: the hop's signing root must be the current
        # root, OR be bridged to it by a rotation proof that covers
        # presentation_time AND enumerates this delegation as surviving.
        if hop.signed_under_root == current_root:
            continue

        bridging = [
            p for p in rotation_proofs
            if p.issuer == hop.issuer
            and p.from_root == hop.signed_under_root
            and p.to_root == current_root
            and p.valid_from <= presentation_time <= p.valid_to
        ]
        if not bridging:
            raise AnchorStaleDelegationError(
                f"hop {hop.issuer}->{hop.subject} signed under "
                f"{hop.signed_under_root} but current root is "
                f"{current_root} at epoch {current_epoch} with no "
                f"bridging rotation proof covering t={presentation_time}"
            )

        # Even a bridging proof is insufficient unless it attests that
        # THIS delegation survives the rotation. A proof that supersedes
        # the root for new issuances does not re-attest old grants.
        if not any(
            hop.subject in p.surviving_delegations for p in bridging
        ):
            raise AnchorStaleDelegationError(
                f"rotation proof for {hop.issuer} does not enumerate "
                f"delegation to {hop.subject} as surviving; authority "
                f"was superseded at rotation, not inherited"
            )
