# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-aaif-attestation-chain-whose-leaf-warrant-is-valid-but-whose-delegation-depth-counter-has-drifted-across-a-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-aaif-attestation-chain-whose-leaf-warrant-is-valid-but-whose-delegation-depth-counter-has-drifted-across-a-re-issuance.warrant.json
# Markdown SHA-256:   5650fa037f61f778532f0ea2e26670a475baae291e87d5f3a54af3f113124ca2
# Code AST SHA-256:   b121565142bb917a4ae690fe4d961263d2383ba7e41bd680d075ad4a77a90b0e
# Verified Classes:   AttestationChainDriftError, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import List


class AttestationChainDriftError(RuntimeError):
    """Raised when an AAIF chain's walked hop count exceeds the root warrant's max_depth,
    or when a terminal (ddepth==0) node re-issued a child warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject_key: str      # identity of the delegate
    issuer_key: str       # identity of the delegator
    ddepth: int           # declared remaining delegation depth
    is_reissuance: bool   # True if this link re-issued to the same subject_key as its parent


def verify_chain(chain: List[Warrant], root_max_depth: int, max_refresh: int = 1) -> None:
    if not chain:
        raise AttestationChainDriftError("empty attestation chain")

    root = chain[0]
    if root.ddepth != root_max_depth:
        raise AttestationChainDriftError(
            f"root ddepth {root.ddepth} != declared max_depth {root_max_depth}"
        )

    # Count distinct subject-key transitions; self-re-issuance is zero transitions
    # but still consumes a refresh budget and is illegal from a terminal node.
    hops = 0
    refreshes = 0
    prev = root
    for node in chain[1:]:
        if node.issuer_key != prev.subject_key:
            raise AttestationChainDriftError(
                f"broken lineage: issuer {node.issuer_key} != parent subject {prev.subject_key}"
            )
        if node.is_reissuance or node.subject_key == prev.subject_key:
            if prev.ddepth == 0:
                raise AttestationChainDriftError(
                    f"terminal node {prev.subject_key} re-issued (ddepth=0); "
                    "authority travel exceeds root warrant"
                )
            refreshes += 1
            if refreshes > max_refresh:
                raise AttestationChainDriftError(
                    f"re-issuance count {refreshes} exceeds max_refresh {max_refresh}"
                )
        else:
            hops += 1
        prev = node

    # The invariant that per-link signature checks do NOT enforce:
    if hops > root_max_depth:
        raise AttestationChainDriftError(
            f"walked hop count {hops} exceeds root max_depth {root_max_depth}; "
            "ddepth field drifted across re-issuance boundary"
        )


def authorize_settlement(chain: List[Warrant], root_max_depth: int) -> str:
    try:
        verify_chain(chain, root_max_depth)
    except AttestationChainDriftError as e:
        # Hard reject: no irreversible action on a drifted chain.
        raise AttestationChainDriftError(f"settlement refused: {e}") from e
    return "authorized"
