# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-set-is-a-strict-superset-of-the-parent-warrant-s-scope-set.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-set-is-a-strict-superset-of-the-parent-warrant-s-scope-set.warrant.json
# Markdown SHA-256:   6fd02c37a81f035bc4bf9144d174885bfba237f06ff2e6eb7ecc5378953bd0c8
# Code AST SHA-256:   386ebd9540ee64020ab45f9f6900ecf174c7959bc6c785e7ce65f84b40331f70
# Verified Classes:   ScopeAmplificationError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Sequence


class ScopeAmplificationError(RuntimeError):
    """Raised when a delegated AAIF credential's effective authority exceeds
    the intersection of scope sets along its warrant chain, or when a hop
    drops an ancestor caveat, or when a hop's scopes are incomparable."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    scopes: FrozenSet[str]
    caveats: FrozenSet[str]
    parent_hash: str | None


def reconstruct_effective_scopes(chain: Sequence[Warrant]) -> FrozenSet[str]:
    """chain[0] is root, chain[-1] is leaf. Returns the intersection of all
    scope sets, raising if any hop violates monotonicity."""
    if not chain:
        raise ScopeAmplificationError("empty warrant chain")

    effective = chain[0].scopes
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        if not child.scopes.issubset(parent.scopes):
            # Superset is amplification; incomparable is malformed. Both fatal.
            missing = child.scopes - parent.scopes
            raise ScopeAmplificationError(
                f"hop {i} ({child.subject}) amplifies scopes beyond parent "
                f"({parent.subject}): {sorted(missing)}"
            )

        if not parent.caveats.issubset(child.caveats):
            dropped = parent.caveats - child.caveats
            raise ScopeAmplificationError(
                f"hop {i} ({child.subject}) dropped ancestor caveats: "
                f"{sorted(dropped)}"
            )

        effective = effective & child.scopes

    return effective


def authorize(chain: Sequence[Warrant], action: str) -> bool:
    effective = reconstruct_effective_scopes(chain)
    if action not in effective:
        return False
    return True
