# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-continue-an-aaif-delegated-credential-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-continue-an-aaif-delegated-credential-chain.warrant.json
# Markdown SHA-256:   262cd9dbaaf3c2ee1baef42cf54ee730ac8b80434a419053ba4032a6e7dd1f8c
# Code AST SHA-256:   d619bfb19f863b8a192eda965a929a48955bcd5929ccc8fc133eddb825982b64
# Verified Classes:   ChainNonContinuableError, ChainLink
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ChainNonContinuableError(RuntimeError):
    """Raised when an AAIF delegated chain passes per-link checks but
    violates the running-intersection monotonicity invariant."""


@dataclass(frozen=True)
class ChainLink:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    signature_valid: bool


def continue_chain(links: list[ChainLink]) -> FrozenSet[str]:
    if not links:
        raise ChainNonContinuableError("empty chain: no root scope to anchor")

    for i, link in enumerate(links):
        if not link.signature_valid:
            raise ChainNonContinuableError(
                f"link {i} ({link.issuer}->{link.subject}) signature invalid"
            )

    running = links[0].scope
    for i, link in enumerate(links[1:], start=1):
        # Per-link subset check (necessary, not sufficient).
        if not link.scope.issubset(links[i - 1].scope):
            raise ChainNonContinuableError(
                f"link {i} ({link.issuer}->{link.subject}) widens vs immediate parent"
            )
        # Running-intersection check: the actual continuability invariant.
        new_running = running & link.scope
        if new_running != link.scope:
            raise ChainNonContinuableError(
                f"link {i} ({link.issuer}->{link.subject}) re-broadens scope "
                f"beyond running intersection {sorted(running)}; "
                f"declared {sorted(link.scope)}"
            )
        running = new_running

    return running
