# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-present-a-valid-aaif-credential-whose-delegation-chain-no-longer-authorizes-the-requested-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-present-a-valid-aaif-credential-whose-delegation-chain-no-longer-authorizes-the-requested-scope.warrant.json
# Markdown SHA-256:   ea46ec17f013c2450ffe40f3cd44175cd2639e3dce70dc1760a44bce73d7541a
# Code AST SHA-256:   1661082bcb3e9c18748e360d5335f6d11fda92ea4478c28d98f1ad68d0b3d12b
# Verified Classes:   AAIFPathAuthorizationError
# Defensive Guards:   9 fail-closed invariants (zero external deps)

class AAIFPathAuthorizationError(RuntimeError):
    """Raised when an AAIF delegation chain fails path-intersection authorization."""
    pass


def authorize_aaif_chain(chain, requested_action, requested_amount, now, expected_audience):
    """
    chain: list of link dicts, each with keys:
        scope (set[str]), constraints (dict), aud (str), exp (float),
        sig_valid (bool), revoked (bool), depth_remaining (int), structured (bool)
    Returns True iff the requested action is within the path intersection.
    """
    if not chain:
        raise AAIFPathAuthorizationError("empty delegation chain")

    effective_scope = set(chain[0]["scope"])
    effective_max_amount = chain[0]["constraints"].get("max_amount", float("inf"))
    prev_depth = None

    for i, link in enumerate(chain):
        if not link.get("structured", False):
            raise AAIFPathAuthorizationError(
                f"link {i} has unstructured constraints; fail closed"
            )
        if not link["sig_valid"]:
            raise AAIFPathAuthorizationError(f"link {i} signature invalid")
        if link["revoked"]:
            raise AAIFPathAuthorizationError(f"link {i} revoked at epoch {now}")
        if now >= link["exp"]:
            raise AAIFPathAuthorizationError(f"link {i} expired at {link['exp']}")
        if link["aud"] != expected_audience:
            raise AAIFPathAuthorizationError(
                f"link {i} audience {link['aud']} != {expected_audience}"
            )

        effective_scope &= set(link["scope"])
        effective_max_amount = min(
            effective_max_amount, link["constraints"].get("max_amount", float("inf"))
        )

        depth = link.get("depth_remaining")
        if depth is not None:
            if prev_depth is not None and depth > prev_depth:
                raise AAIFPathAuthorizationError(
                    f"link {i} depth {depth} exceeds parent depth {prev_depth}"
                )
            prev_depth = depth

    if requested_action not in effective_scope:
        raise AAIFPathAuthorizationError(
            f"action {requested_action!r} outside path scope intersection {effective_scope}"
        )
    if requested_amount > effective_max_amount:
        raise AAIFPathAuthorizationError(
            f"amount {requested_amount} exceeds path max_amount {effective_max_amount}"
        )
    return True
