# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-scope-chain-diverges-at-a-non-adjacent-issuer-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-credential-whose-scope-chain-diverges-at-a-non-adjacent-issuer-hop.warrant.json
# Markdown SHA-256:   97a0edc0d7c8050c85745b5d106728810aebf04732430c97a2a915317a6dbc03
# Code AST SHA-256:   3b208d1727ed9499d97a929a65b681bea05b62bb50da8dd4c89d0253a6e78a9d
# Verified Classes:   DelegationChainError, Hop, AnchorSnapshot
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when a delegated credential chain fails an AAIF validity invariant."""


@dataclass(frozen=True)
class Hop:
    issuer: str
    signing_key_id: str
    not_before: float
    scope: frozenset


@dataclass(frozen=True)
class AnchorSnapshot:
    version: str
    # key_id -> (valid_from, valid_until_or_None)
    keys: dict
    fetched_at: float


def verify_delegation_chain(
    chain: list[Hop],
    snapshot: AnchorSnapshot,
    now: float,
    max_staleness: float,
    grace_period: float,
) -> dict:
    if not chain:
        raise DelegationChainError("empty delegation chain")

    # Condition 5: verifier cannot reason about liveness on a stale snapshot.
    if (now - snapshot.fetched_at) > max_staleness:
        raise DelegationChainError(
            f"anchor snapshot v{snapshot.version} stale by "
            f"{now - snapshot.fetched_at:.1f}s > max_staleness {max_staleness}s; "
            "fail-closed, retryable"
        )

    degraded = False
    for idx, hop in enumerate(chain):
        entry = snapshot.keys.get(hop.signing_key_id)
        if entry is None:
            # Condition 2: key never trusted at issuance -> terminal-invalid.
            raise DelegationChainError(
                f"hop {idx}: signing key {hop.signing_key_id} absent from anchor "
                f"snapshot v{snapshot.version}; chain is terminal-invalid"
            )
        valid_from, valid_until = entry

        # Condition 2: anchor liveness at issuance.
        if hop.not_before < valid_from:
            raise DelegationChainError(
                f"hop {idx}: credential minted at {hop.not_before} before key "
                f"{hop.signing_key_id} became trusted at {valid_from}"
            )

        # Condition 3: anchor liveness at verification, with grace window.
        if valid_until is not None and now > valid_until:
            if hop.not_before <= valid_until and (now - valid_until) <= grace_period:
                degraded = True
            else:
                raise DelegationChainError(
                    f"hop {idx}: key {hop.signing_key_id} revoked at {valid_until}; "
                    f"now={now}, grace={grace_period}s exceeded or predates issuance"
                )

        # Condition 4: scope monotonicity against narrowest ancestor.
        if idx > 0 and not hop.scope <= chain[idx - 1].scope:
            raise DelegationChainError(
                f"hop {idx}: scope {set(hop.scope)} not a subset of parent "
                f"{set(chain[idx - 1].scope)}"
            )

    return {
        "admitted": True,
        "degraded_trust": degraded,
        "anchor_snapshot_version": snapshot.version,
    }
