# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-aaif-delegated-credential-exchange-as-non-transitive.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-aaif-delegated-credential-exchange-as-non-transitive.warrant.json
# Markdown SHA-256:   213c469052fcc360ebd91e283bb1e7990cad4a85fbb1f7845196bc7f87231c0c
# Code AST SHA-256:   cd16212923e2fdf2aa0cd835f88439cb106b72903377bb0dfd6596d771b7c390
# Verified Classes:   AAIFDelegationError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class AAIFDelegationError(RuntimeError):
    """Raised when an AAIF delegated credential chain is cryptographically valid
    but not authorized for the target resource's trust domain."""
    pass


def authorize_delegated_chain(chain, resource_id, resource_trust_domain, max_depth):
    """
    chain: list of hop dicts, ordered principal -> ... -> terminal issuer.
    Each hop: {"agent_id", "trust_domain", "aud", "delegation_allowed",
               "delegation_scope": set[str], "signature_valid": bool}
    """
    if len(chain) > max_depth:
        raise AAIFDelegationError(
            f"chain length {len(chain)} exceeds max_delegation_depth {max_depth}"
        )

    for i, hop in enumerate(chain):
        if not hop.get("signature_valid", False):
            raise AAIFDelegationError(f"hop {i} signature invalid")
        if not hop.get("delegation_allowed", False):
            raise AAIFDelegationError(
                f"hop {i} ({hop['agent_id']}) does not permit delegation"
            )

    # Walk hops; each issuer must have delegated to the next hop's trust domain.
    for i in range(len(chain) - 1):
        issuer = chain[i]
        next_hop = chain[i + 1]
        if issuer["aud"] != next_hop["agent_id"]:
            raise AAIFDelegationError(
                f"hop {i} aud {issuer['aud']!r} != next agent {next_hop['agent_id']!r}"
            )
        if next_hop["trust_domain"] not in issuer["delegation_scope"]:
            raise AAIFDelegationError(
                f"hop {i} delegation_scope does not cover trust domain "
                f"{next_hop['trust_domain']!r}; non-transitive delegation"
            )

    terminal = chain[-1]
    if terminal["aud"] != resource_id:
        raise AAIFDelegationError(
            f"terminal aud {terminal['aud']!r} != resource {resource_id!r}"
        )
    if resource_trust_domain not in terminal["delegation_scope"]:
        raise AAIFDelegationError(
            f"penultimate delegation_scope does not cover resource trust domain "
            f"{resource_trust_domain!r}"
        )

    return True
