# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-of-an-aaif-delegation-chain-is-re-signed-by-a-vendor-whose-trust-anchor-has-rotated-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-of-an-aaif-delegation-chain-is-re-signed-by-a-vendor-whose-trust-anchor-has-rotated-mid-flight.warrant.json
# Markdown SHA-256:   a90897e07acd052e536b8900389d64f1729b4fed269e9c3a06a6685dc883ab12
# Code AST SHA-256:   4456962dc5374f9d24c19c48a536039341d5fb5c2c75eca78df6b4650ef6c2ef
# Verified Classes:   DelegationChainAnchorError, Credential, AnchorRotation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class DelegationChainAnchorError(RuntimeError):
    """Raised when a delegation chain's signing anchor is not trusted at verification time."""
    pass


@dataclass
class Credential:
    issuer: str
    anchor_id: str
    issuance: datetime
    expiration: datetime
    signature_valid: bool


@dataclass
class AnchorRotation:
    issuer: str
    retired_anchor_id: str
    rotated_at: datetime
    authenticated: bool


GRACE_WINDOW = timedelta(seconds=300)


def verify_chain(
    chain: list[Credential],
    current_anchors: dict[str, set[str]],
    rotations: list[AnchorRotation],
    now: datetime,
) -> bool:
    for cred in chain:
        if not cred.signature_valid:
            raise DelegationChainAnchorError(
                f"signature invalid for {cred.issuer} anchor {cred.anchor_id}"
            )
        if cred.expiration <= now:
            raise DelegationChainAnchorError(
                f"credential from {cred.issuer} expired at {cred.expiration}"
            )

        trusted = current_anchors.get(cred.issuer, set())
        if cred.anchor_id in trusted:
            continue

        # Anchor not currently trusted; check for an authenticated grace rotation.
        rotation = next(
            (r for r in rotations
             if r.issuer == cred.issuer and r.retired_anchor_id == cred.anchor_id),
            None,
        )
        if rotation is None:
            raise DelegationChainAnchorError(
                f"anchor {cred.anchor_id} for {cred.issuer} untrusted and no rotation record"
            )
        if not rotation.authenticated:
            raise DelegationChainAnchorError(
                f"rotation for {cred.issuer} anchor {cred.anchor_id} not authenticated; fail closed"
            )
        if cred.issuance >= rotation.rotated_at:
            raise DelegationChainAnchorError(
                f"credential from {cred.issuer} signed after anchor retirement; unauthorized at signing"
            )
        if now - rotation.rotated_at > GRACE_WINDOW:
            raise DelegationChainAnchorError(
                f"grace window exceeded for {cred.issuer} anchor {cred.anchor_id}"
            )
    return True
