# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-stop-trusting-a-delegated-aaif-credential-chain-the-depth-versus-intersection-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-stop-trusting-a-delegated-aaif-credential-chain-the-depth-versus-intersection-invariant.warrant.json
# Markdown SHA-256:   a89f4aa97a2eae60b73c89aaca71e676e5a13a6b939751644a851b62f526f154
# Code AST SHA-256:   d54749ed5b109416001096a305536689d7c54cddb413b4d358c22245a22b199c
# Verified Classes:   AAIFChainViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class AAIFChainViolation(RuntimeError):
    """Raised when a delegated AAIF credential chain fails the root-anchored fold."""
    pass


def validate_chain(chain, max_delegation_depth):
    # chain[0] is the root resource-owner grant; chain[-1] is the leaf credential.
    # Each element exposes: .scopes (frozenset[str]), .cnf_key, .issuer_key, .act (list[str])
    if not chain:
        raise AAIFChainViolation("empty chain")
    if len(chain) > max_delegation_depth:
        raise AAIFChainViolation(
            f"signed depth {len(chain)} exceeds max {max_delegation_depth}"
        )

    trusted = frozenset(chain[0].scopes)
    for i in range(1, len(chain)):
        hop = chain[i]
        prev = chain[i - 1]

        if hop.issuer_key != prev.cnf_key:
            raise AAIFChainViolation(f"cnf linkage broken at hop {i}")

        if len(hop.act) != i:
            raise AAIFChainViolation(
                f"act nesting length {len(hop.act)} != signed depth {i} at hop {i}"
            )

        hop_scopes = frozenset(hop.scopes)
        if not hop_scopes.issubset(trusted):
            widened = hop_scopes - trusted
            raise AAIFChainViolation(
                f"scope widening at hop {i}: {sorted(widened)} not granted upstream"
            )
        # Narrowing (or equality) is the only admissible transition.
        trusted = hop_scopes

    return trusted


def authorize(chain, requested_scope, max_delegation_depth):
    trusted = validate_chain(chain, max_delegation_depth)
    if requested_scope not in trusted:
        raise AAIFChainViolation(
            f"requested scope {requested_scope!r} outside trusted set {sorted(trusted)}"
        )
    return True
