# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-credential-chain-breakage-before-scope-violation-surfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-credential-chain-breakage-before-scope-violation-surfaces.warrant.json
# Markdown SHA-256:   91d2cd1147f44e126c3fab59b31c1452c8815cc1c6b6718660f9ec78f865cb7b
# Code AST SHA-256:   b95faffb883a15f628eb9b48feb0d152d000be0edc0d746e48a6f93a20ad9b7e
# Verified Classes:   DelegatedChainStructuralError, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Sequence


class DelegatedChainStructuralError(RuntimeError):
    """Raised when a delegated credential chain is structurally broken
    even though leaf scope validation passed. Indicates an authority-
    attribution failure, not a scope violation."""


@dataclass(frozen=True)
class Hop:
    sub: str          # subject of this hop
    act: str          # actor asserted by this hop (must equal parent.sub)
    iat: float        # issued-at, seconds
    del_remaining: int
    rev_list_id: str  # revocation list covering this hop's issuer


def validate_chain(chain: Sequence[Hop], leaf_scope_valid: bool) -> None:
    if not leaf_scope_valid:
        raise DelegatedChainStructuralError(
            "leaf scope invalid; this is a scope failure, not a chain failure"
        )
    if not chain:
        raise DelegatedChainStructuralError("empty delegated chain")

    # Invariant 1: strict act == parent.sub
    for i in range(1, len(chain)):
        if chain[i].act != chain[i - 1].sub:
            raise DelegatedChainStructuralError(
                f"hop {i} actor {chain[i].act!r} != hop {i-1} subject "
                f"{chain[i-1].sub!r}; chain cannot reconstruct"
            )

    # Invariant 2: delegation depth decrements by exactly one
    for i in range(1, len(chain)):
        if chain[i].del_remaining != chain[i - 1].del_remaining - 1:
            raise DelegatedChainStructuralError(
                f"hop {i} depth {chain[i].del_remaining} does not equal "
                f"hop {i-1} depth {chain[i-1].del_remaining} - 1"
            )

    # Invariant 3: strictly increasing iat along the chain
    for i in range(1, len(chain)):
        if chain[i].iat <= chain[i - 1].iat:
            raise DelegatedChainStructuralError(
                f"hop {i} iat {chain[i].iat} not strictly after "
                f"hop {i-1} iat {chain[i-1].iat}"
            )

    # Invariant 4: every hop's issuer revocation list is referenced
    covered = {h.rev_list_id for h in chain}
    if len(covered) != len(chain):
        raise DelegatedChainStructuralError(
            "revocation coverage gap: not every hop issuer's list is "
            f"referenced (covered={sorted(covered)})"
        )
