# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-narrows-mid-chain-the-attenuation-monotonicity-invariant-and-its-sil.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-narrows-mid-chain-the-attenuation-monotonicity-invariant-and-its-sil.warrant.json
# Markdown SHA-256:   eb7139d9a6467152ab8a251a8649a01a7d1061295881141a85c08b6b1d4192b9
# Code AST SHA-256:   09c510d51845115208caab2e10e8023d8726a8d594634ce7ad30579aab426f18
# Verified Classes:   AttenuationViolation, Scope, Credential
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class AttenuationViolation(RuntimeError):
    """Raised when a delegated AAIF credential fails monotonicity under the root's normalizers."""


@dataclass(frozen=True)
class Scope:
    resources: FrozenSet[str]
    actions: FrozenSet[str]
    normalizer_version: str
    matcher: str  # "single_segment" | "recursive"


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: Scope
    parent_id: Optional[str]
    depth: int
    schema_uri: str
    proof_of_attenuation: Optional[str] = None


ROOT_NORMALIZER = {"v1": {"read": {"read"}, "list": {"list"}, "read_write": {"read", "write"}}}


def _normalize_actions(actions: FrozenSet[str], version: str) -> FrozenSet[str]:
    table = ROOT_NORMALIZER.get(version)
    if table is None:
        raise AttenuationViolation(f"unknown normalizer version {version!r}; cannot verify subset")
    out: set = set()
    for a in actions:
        if a not in table:
            raise AttenuationViolation(f"action {a!r} has no normalizer entry under {version}")
        out |= table[a]
    return frozenset(out)


def _resource_subset(child: FrozenSet[str], parent: FrozenSet[str], matcher: str) -> bool:
    # Conservative: every child glob must be provably contained in some parent glob
    # under the SAME matcher. Recursive/single-segment mixing is treated as widening.
    for c in child:
        if not any(_glob_contains(p, c, matcher) for p in parent):
            return False
    return True


def _glob_contains(parent_glob: str, child_glob: str, matcher: str) -> bool:
    if matcher == "single_segment":
        # '*' does not cross '/'. Child may not introduce '**' or deeper segments.
        if "**" in child_glob:
            return False
        p_prefix = parent_glob.split("*", 1)[0]
        return child_glob.startswith(p_prefix) and child_glob.count("/") == parent_glob.count("/")
    if matcher == "recursive":
        p_prefix = parent_glob.split("*", 1)[0]
        return child_glob.startswith(p_prefix)
    raise AttenuationViolation(f"unknown matcher {matcher!r}")


def verify_delegation(child: Credential, parent: Credential, root: Credential) -> None:
    """Reject unless child is a provable attenuation of parent under ROOT's normalizers."""
    if root.scope.normalizer_version != parent.scope.normalizer_version:
        raise AttenuationViolation("parent normalizer version diverges from root")
    if child.scope.normalizer_version != root.scope.normalizer_version:
        raise AttenuationViolation(
            f"child normalizer {child.scope.normalizer_version!r} != root "
            f"{root.scope.normalizer_version!r}; re-mint may have widened"
        )
    if child.scope.matcher != root.scope.matcher:
        raise AttenuationViolation(
            f"matcher drift {child.scope.matcher!r} vs root {root.scope.matcher!r}"
        )
    if child.depth > root.depth:
        raise AttenuationViolation(f"depth {child.depth} exceeds root budget {root.depth}")

    # Action attenuation: child actions must be a subset of parent actions pre-normalization,
    # then the normalized sets must also be subsets.
    if not child.scope.actions.issubset(parent.scope.actions | _normalize_actions(parent.scope.actions, root.scope.normalizer_version)):
        raise AttenuationViolation(
            f"action widening: child={sorted(child.scope.actions)} parent={sorted(parent.scope.actions)}"
        )
    if not _normalize_actions(child.scope.actions, root.scope.normalizer_version).issubset(
        _normalize_actions(parent.scope.actions, root.scope.normalizer_version)
    ):
        raise AttenuationViolation("normalized action set escapes parent")

    if not _resource_subset(child.scope.resources, parent.scope.resources, root.scope.matcher):
        raise AttenuationViolation(
            f"resource widening: child={sorted(child.scope.resources)} "
            f"parent={sorted(parent.scope.resources)} matcher={root.scope.matcher}"
        )


def admit(chain: list[Credential]) -> Credential:
    """Validate a full delegation chain against its root; return the leaf on success."""
    if not chain:
        raise AttenuationViolation("empty chain")
    root = chain[0]
    for i in range(1, len(chain)):
        verify_delegation(chain[i], chain[i - 1], root)
    return chain[-1]
