# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-aaif-attestation-chain-when-the-delegating-principal-s-key-has-been-rotated-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-aaif-attestation-chain-when-the-delegating-principal-s-key-has-been-rotated-mid-chain.warrant.json
# Markdown SHA-256:   51029284420cec64a5bca70dbe070e31d5d6e498f622a3cf050f0e38a4fc1037
# Code AST SHA-256:   8255b283c16bfc0959a5228bde4a94ab2c1396e55d987a31f05563fada4e928d
# Verified Classes:   AttestationChainError, KeyInterval, Link
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttestationChainError(RuntimeError):
    """Raised when a delegated attestation chain cannot be validly verified."""


@dataclass(frozen=True)
class KeyInterval:
    key_id: str
    active_from: float
    revoked_at: Optional[float]  # None == not revoked


@dataclass(frozen=True)
class Link:
    principal: str
    delegate: str
    scope: str
    signed_at: float
    expires_at: float
    signing_key_id: str
    signature: bytes


def _key_active_at(intervals: list[KeyInterval], key_id: str, t: float) -> bool:
    for iv in intervals:
        if iv.key_id != key_id:
            continue
        if iv.active_from <= t and (iv.revoked_at is None or t < iv.revoked_at):
            return True
    return False


def verify_link(link: Link, intervals: list[KeyInterval], now: float,
                signature_ok: bool) -> None:
    # Reject if the registry cannot express signing-time validity.
    if not intervals:
        raise AttestationChainError(
            "key registry exposes no validity intervals; cannot verify at signing time"
        )
    if link.signed_at > now:
        raise AttestationChainError(
            f"link signed_at {link.signed_at} is in the future relative to now {now}"
        )
    if link.expires_at <= now:
        raise AttestationChainError(
            f"link expired at {link.expires_at}, now {now}"
        )
    if not _key_active_at(intervals, link.signing_key_id, link.signed_at):
        # This is the rotation boundary: key may be revoked *now* but was
        # active at signing time. If it was not active at signing time, reject.
        raise AttestationChainError(
            f"signing key {link.signing_key_id} was not active at signed_at "
            f"{link.signed_at}; refusing (do not fall back to re-signed substitute)"
        )
    if not signature_ok:
        raise AttestationChainError(
            f"signature invalid for link {link.principal}->{link.delegate}"
        )


def verify_chain(chain: list[Link], intervals: list[KeyInterval], now: float,
                 signatures_ok: list[bool]) -> None:
    if len(chain) != len(signatures_ok):
        raise AttestationChainError("signature vector length mismatch with chain")
    for link, ok in zip(chain, signatures_ok):
        verify_link(link, intervals, now, ok)
