# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-scope-whose-attenuation-chain-is-valid-but-whose-bounding-principal-has-been-re-keyed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-scope-whose-attenuation-chain-is-valid-but-whose-bounding-principal-has-been-re-keyed.warrant.json
# Markdown SHA-256:   692fbb23c17651697718f6a0035abd3e446a689c7c553859f6536bb8fe4784c4
# Code AST SHA-256:   ceac075a038f4d822e062e9157ed1ed6515b93d3bde82cd606025480a8b156b2
# Verified Classes:   DelegationChainOrphanedError, RotationRecord, DelegationHop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationChainOrphanedError(RuntimeError):
    """Raised when a delegation chain's bounding principal has been re-keyed
    and the rotation record does not carry forward continuity for this lineage."""
    pass


@dataclass(frozen=True)
class RotationRecord:
    principal: str
    old_key_fingerprint: str
    new_key_fingerprint: str
    # None means the schema predates continuity support.
    continuity_lineages: frozenset[str] | None


@dataclass(frozen=True)
class DelegationHop:
    issuer_key_fingerprint: str
    scope: str
    lineage_id: str


def verify_delegation_chain(
    chain: list[DelegationHop],
    principal: str,
    rotation_history: list[RotationRecord],
    current_epoch: int,
    cached_epoch: int | None,
) -> bool:
    if not chain:
        raise DelegationChainOrphanedError("empty delegation chain")

    root_fingerprint = chain[0].issuer_key_fingerprint
    lineage_id = chain[0].lineage_id

    # Cache epoch must match the principal's current rotation epoch.
    if cached_epoch is not None and cached_epoch != current_epoch:
        raise DelegationChainOrphanedError(
            f"cached verification from epoch {cached_epoch} is stale; "
            f"principal {principal} is at epoch {current_epoch}"
        )

    retired = {r.old_key_fingerprint for r in rotation_history if r.principal == principal}

    if root_fingerprint not in retired:
        # Chain minted under a currently-live key: no continuity question.
        return True

    # Root key is retired. Find the rotation that retired it and demand
    # explicit lineage continuity. Absence of a continuity field is NOT
    # permission to proceed.
    for record in rotation_history:
        if record.principal != principal:
            continue
        if record.old_key_fingerprint != root_fingerprint:
            continue
        if record.continuity_lineages is None:
            raise DelegationChainOrphanedError(
                f"rotation record for {principal} predates continuity schema; "
                f"cannot prove lineage {lineage_id} survived re-keying"
            )
        if lineage_id not in record.continuity_lineages:
            raise DelegationChainOrphanedError(
                f"lineage {lineage_id} not carried forward by rotation of {principal}; "
                f"chain is orphaned under retired key {root_fingerprint}"
            )
        return True

    raise DelegationChainOrphanedError(
        f"root key {root_fingerprint} is retired for {principal} but no matching "
        f"rotation record was found to establish continuity"
    )
