# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attenuate-an-aaif-delegated-credential-chain-and-how-does-scope-narrowing-silently-invert-at-the-intersec.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-attenuate-an-aaif-delegated-credential-chain-and-how-does-scope-narrowing-silently-invert-at-the-intersec.warrant.json
# Markdown SHA-256:   00c28c8768e3db969f113fba5c896260de3ce626468aa6bcfab6de42b091be96
# Code AST SHA-256:   29ac35d122247521a0b9dbe5cb98456ea4a5221670fa731f059a20abb42295d8
# Verified Classes:   AttenuationInvariantViolation, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AttenuationInvariantViolation(RuntimeError):
    """Raised when a child credential cannot be proven at-least-as-restrictive
    as its parent for every constraint kind the parent carries."""
    pass


@dataclass(frozen=True)
class Credential:
    positive_scope: FrozenSet[str]
    # None means "inherit from parent"; an explicit empty frozenset means
    # "assert no restriction" and is only legal if the parent's is also empty.
    deny_paths: Optional[FrozenSet[str]] = None
    # Cumulative: remaining budget, not total. None means inherit.
    remaining_calls: Optional[int] = None
    # Any constraint kind the minting instance does not understand must be
    # surfaced here so the gate can refuse rather than pass it through.
    unknown_constraint_kinds: FrozenSet[str] = field(default_factory=frozenset)


KNOWN_CONSTRAINT_KINDS = frozenset({"deny_paths", "remaining_calls"})


def attenuate(parent: Credential, child_request: Credential) -> Credential:
    # 1. Unknown constraint kinds in the parent cannot be narrowed -> refuse.
    unsupported = parent.unknown_constraint_kinds - KNOWN_CONSTRAINT_KINDS
    if unsupported:
        raise AttenuationInvariantViolation(
            f"parent carries unsupported constraint kinds {sorted(unsupported)}; "
            f"cannot prove child is at-least-as-restrictive"
        )

    # 2. Positive scope must be a subset (the obvious check).
    if not child_request.positive_scope <= parent.positive_scope:
        raise AttenuationInvariantViolation(
            "child positive scope exceeds parent positive scope"
        )

    # 3. Deny-list: absent means inherit; explicit empty is legal only if
    #    parent's deny-list is also empty. Dropping a parent deny-list widens.
    if child_request.deny_paths is None:
        effective_deny = parent.deny_paths
    else:
        if parent.deny_paths and not child_request.deny_paths:
            raise AttenuationInvariantViolation(
                "child explicitly emptied a non-empty parent deny_paths; "
                "this is amplification, not attenuation"
            )
        if child_request.deny_paths != parent.deny_paths and not (
            child_request.deny_paths >= (parent.deny_paths or frozenset())
        ):
            raise AttenuationInvariantViolation(
                "child deny_paths is not a superset of parent deny_paths"
            )
        effective_deny = child_request.deny_paths

    # 4. Cumulative budget: child must carry remaining <= parent remaining.
    if parent.remaining_calls is not None:
        if child_request.remaining_calls is None:
            effective_remaining = parent.remaining_calls
        elif child_request.remaining_calls > parent.remaining_calls:
            raise AttenuationInvariantViolation(
                f"child remaining_calls {child_request.remaining_calls} exceeds "
                f"parent remaining {parent.remaining_calls}; per-credential "
                f"budgets are not chain-bounded"
            )
        else:
            effective_remaining = child_request.remaining_calls
    else:
        effective_remaining = child_request.remaining_calls

    return Credential(
        positive_scope=child_request.positive_scope,
        deny_paths=effective_deny,
        remaining_calls=effective_remaining,
        unknown_constraint_kinds=frozenset(),
    )
