# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-every-verifiable-credential-in-it-still-verifies.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-every-verifiable-credential-in-it-still-verifies.warrant.json
# Markdown SHA-256:   1b64d8a49c38e4242bc78ce5848889d7431e5ad26464de0818b397262b037883
# Code AST SHA-256:   b28dd73abc111e2522208f2e50d422455985d506d2afc4bbfc276135e966a43f
# Verified Classes:   DelegationChainIntegrityError, Hop, ResolvedMethod
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class DelegationChainIntegrityError(RuntimeError):
    """Raised when a delegation chain is signature-valid but join-invalid."""
    pass

@dataclass
class Hop:
    issuer: str          # e.g. "did:web:sub.example#key-2" or "did:web:sub.example"
    subject: str
    nbf: int
    exp: int
    signature_ok: bool   # result of per-link crypto verification

@dataclass
class ResolvedMethod:
    did: str
    fragment: str
    current: bool
    retired: bool
    valid_from: int

def _split_key_scoped(identifier: str) -> tuple[str, Optional[str]]:
    if "#" in identifier:
        did, frag = identifier.split("#", 1)
        return did, frag
    return identifier, None

def verify_chain_joins(
    chain: list[Hop],
    resolver,  # callable(did) -> list[ResolvedMethod]
    now: int,
) -> None:
    """
    Enforce key-scoped continuity across every adjacent hop.
    Rejects DID-scoped joins where method identity is ambiguous.
    """
    if not chain:
        raise DelegationChainIntegrityError("empty delegation chain")

    for i, hop in enumerate(chain):
        if not hop.signature_ok:
            raise DelegationChainIntegrityError(
                f"hop {i}: signature invalid"
            )
        if not (hop.nbf <= now <= hop.exp):
            raise DelegationChainIntegrityError(
                f"hop {i}: temporal window violated"
            )

    for i in range(len(chain) - 1):
        parent, child = chain[i], chain[i + 1]

        p_did, p_frag = _split_key_scoped(parent.subject)
        c_did, c_frag = _split_key_scoped(child.issuer)

        # Invariant 1: parent subject must name a specific verification method.
        if p_frag is None:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: parent subject {parent.subject!r} is DID-scoped; "
                "cannot establish key continuity across rotation"
            )

        # Invariant 2: child issuer must name the exact same method.
        if c_frag is None:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: child issuer {child.issuer!r} is DID-scoped; "
                "join is ambiguous under re-provisioning"
            )

        if (p_did, p_frag) != (c_did, c_frag):
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: subject {parent.subject!r} != issuer {child.issuer!r}"
            )

        # Invariant 3: the named method must be current, not retired, at signing
        # and at verification time.
        methods = resolver(c_did)
        match = [m for m in methods if m.fragment == c_frag]
        if not match:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: method {child.issuer!r} not found in DID document"
            )
        m = match[0]
        if m.retired:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: method {child.issuer!r} is retired; "
                "principal identity may have been reassigned"
            )
        if not m.current:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: method {child.issuer!r} not current at verification"
            )
        if m.valid_from > child.nbf:
            raise DelegationChainIntegrityError(
                f"hop {i}->{i+1}: method {child.issuer!r} did not exist at hop signing time"
            )

    # Invariant 4: no unproven rotation between earliest nbf and now.
    earliest = min(h.nbf for h in chain)
    for hop in chain:
        did, _ = _split_key_scoped(hop.issuer)
        for m in resolver(did):
            if m.valid_from > earliest and not m.current:
                raise DelegationChainIntegrityError(
                    f"rotation event on {did} within chain lifetime without rotation-proof"
                )
