# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-aaif-credential-whose-scope-chain-is-valid-per-issuer-but-the-intersection-of-delegated-scopes-is-e.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-delegated-aaif-credential-whose-scope-chain-is-valid-per-issuer-but-the-intersection-of-delegated-scopes-is-e.warrant.json
# Markdown SHA-256:   5e92a68fc53e89ff0c9e511c2d03a4f03bcdfa7a7cff994ff867aa8eb6962d11
# Code AST SHA-256:   e8119fcc8ae7fc2949f3e2a57f08c5a7097f459a7edd046fa71b2c6658e4a4a7
# Verified Classes:   EmptyScopeIntersectionError, Scope, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple


class EmptyScopeIntersectionError(RuntimeError):
    """Raised when a delegated AAIF chain verifies per-hop but yields an
    empty canonical-resource intersection at the terminal verifier."""


@dataclass(frozen=True)
class Scope:
    resource_uri: str
    action: str

    def canonical(self) -> Tuple[str, str]:
        return (self.resource_uri, self.action)


@dataclass(frozen=True)
class Hop:
    issuer: str
    scopes: FrozenSet[Scope]


def canonical_intersection(chain: Tuple[Hop, ...]) -> FrozenSet[Scope]:
    if not chain:
        return frozenset()
    effective = {s.canonical() for s in chain[0].scopes}
    for hop in chain[1:]:
        effective &= {s.canonical() for s in hop.scopes}
    return frozenset(
        Scope(uri, act) for (uri, act) in effective
    )


def admit(chain: Tuple[Hop, ...]) -> FrozenSet[Scope]:
    # Per-hop signatures, expiry, and trust anchors are assumed already
    # verified upstream. This gate enforces only the intersection invariant.
    effective = canonical_intersection(chain)
    if not effective:
        issuers = " -> ".join(h.issuer for h in chain)
        raise EmptyScopeIntersectionError(
            f"AAIF chain [{issuers}] verified per-hop but canonical scope "
            f"intersection is empty; admitting would grant zero authority "
            f"under a valid credential."
        )
    return effective


def delegate(parent: Hop, child: Hop) -> Hop:
    # Issue-time guard: refuse to mint a child whose intersection with the
    # parent's effective authority is empty.
    if not canonical_intersection((parent, child)):
        raise EmptyScopeIntersectionError(
            f"refusing to mint delegated credential from {parent.issuer} "
            f"to {child.issuer}: empty canonical intersection"
        )
    return child
