# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-aaif-delegation-token-whose-proof-of-possession-key-was-rebound-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-aaif-delegation-token-whose-proof-of-possession-key-was-rebound-mid-chain.warrant.json
# Markdown SHA-256:   40a26fb4619fd78df56c8fcbbcfccaf557390d4e8475426d30477f2a66e3146a
# Code AST SHA-256:   fac03cee2b5015f0a932bbc8073cf5140164d8b2f9bd73bdbe8a42b8fc21d230
# Verified Classes:   PoPRebindingError, PoPRotationAmbiguous, PoPChainUnverifiable, Hop
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class PoPRebindingError(RuntimeError):
    """Raised when a child hop's cnf.jkt does not match the parent's
    authorized_subject.jkt and no signed key_rotation event bridges them.
    This is indistinguishable from forgery and must be treated as terminal."""
    pass


class PoPRotationAmbiguous(RuntimeError):
    """Raised when a key_rotation event exists but its own PoP proof
    does not verify. The rotation claim may be attacker-injected."""
    pass


class PoPChainUnverifiable(RuntimeError):
    """Raised when the verifier requires chain-consistency but was
    presented only a leaf token with no parent delegation block."""
    pass


@dataclass
class Hop:
    cnf_jkt: str                      # key this hop is bound to (self-description)
    authorized_subject_jkt: Optional[str]  # key this hop delegates TO (authorization)
    signature_valid: bool
    rotation_from_jkt: Optional[str] = None
    rotation_signature_valid: bool = False


def verify_chain(hops: list[Hop], require_full_chain: bool = True) -> bool:
    if not hops:
        raise PoPChainUnverifiable("empty delegation chain")

    # (a) every hop self-consistent
    for i, h in enumerate(hops):
        if not h.signature_valid:
            raise PoPRebindingError(f"hop {i}: signature does not verify against cnf.jkt")

    # leaf-only presentation cannot satisfy chain-consistency
    if len(hops) == 1:
        if require_full_chain:
            raise PoPChainUnverifiable(
                "leaf-only token presented to chain-consistency verifier"
            )
        return True

    # (b) chain-consistent PoP across every adjacent edge
    for i in range(len(hops) - 1):
        parent, child = hops[i], hops[i + 1]
        if parent.authorized_subject_jkt is None:
            raise PoPRebindingError(
                f"hop {i}: missing delegation.authorized_subject; cannot cross-check"
            )
        if child.cnf_jkt == parent.authorized_subject_jkt:
            continue  # direct binding, no rotation
        # mismatch: only a valid signed rotation event can bridge it
        if child.rotation_from_jkt is None:
            raise PoPRebindingError(
                f"hop {i}->{i+1}: cnf.jkt={child.cnf_jkt} != "
                f"authorized_subject.jkt={parent.authorized_subject_jkt} "
                f"with no rotation event; treating as forgery"
            )
        if child.rotation_from_jkt != parent.authorized_subject_jkt:
            raise PoPRebindingError(
                f"hop {i}->{i+1}: rotation claims to originate from "
                f"{child.rotation_from_jkt}, not from parent-authorized "
                f"{parent.authorized_subject_jkt}"
            )
        if not child.rotation_signature_valid:
            raise PoPRotationAmbiguous(
                f"hop {i}->{i+1}: rotation event present but its PoP proof "
                f"does not verify; rotation may be attacker-injected"
            )
    return True
