# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-narrows-correctly-but-whose-cross-issuer-trust-chain-re-broadens-at-an-intermedia.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-narrows-correctly-but-whose-cross-issuer-trust-chain-re-broadens-at-an-intermedia.warrant.json
# Markdown SHA-256:   0af33676a81c1a677f7be78c6729975a0a0a4e6434e0688b406b9cb0edc106ff
# Code AST SHA-256:   87cf13277c7e242304901bac19a34e36dbd6c70c82e5ebc8c0afd1dd05cdfbf5
# Verified Classes:   DelegationNamespaceEscape, DelegationNamespaceUnprovable
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationNamespaceEscape(RuntimeError):
    """Raised when a delegated AAIF credential's requested resource falls
    outside the namespace intersection accumulated across the trust chain."""


class DelegationNamespaceUnprovable(RuntimeError):
    """Raised when an intermediate hop's namespace constraint cannot be
    recovered, so the accumulated intersection cannot be computed."""


def validate_delegated_credential(chain, target_resource):
    # chain: ordered root-first list of hop dicts, each with
    #   'issuer', 'scope' (set[str]), 'authorized_namespaces' (set[str] | None),
    #   'namespace_constraint' (set[str] | None)
    if not chain:
        raise DelegationNamespaceUnprovable("empty chain")

    root = chain[0]
    accumulated = set(root["authorized_namespaces"] or [])

    for hop in chain[1:]:
        hop_ns = hop.get("authorized_namespaces")
        if hop_ns is None and hop.get("namespace_constraint") is None:
            # unqualified scope with no recoverable namespace cap:
            # cannot prove this hop was authorized over the resource partition
            raise DelegationNamespaceUnprovable(
                f"hop {hop['issuer']} has no namespace constraint"
            )
        constraint = hop.get("namespace_constraint") or hop_ns or set()
        accumulated &= set(constraint)
        if not accumulated:
            raise DelegationNamespaceEscape(
                f"namespace intersection empty at hop {hop['issuer']}"
            )

    requested_ns = resolve_namespace(target_resource)
    if requested_ns not in accumulated:
        raise DelegationNamespaceEscape(
            f"resource namespace {requested_ns!r} outside accumulated "
            f"intersection {sorted(accumulated)!r}"
        )
    return True


def resolve_namespace(target_resource):
    # derive partition from the resource URI; must not default to root scope
    return target_resource.split("/")[2]
