# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-warrant-whose-signature-chain-verifies-but-whose-authority-scope-silently-widens-at-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-warrant-whose-signature-chain-verifies-but-whose-authority-scope-silently-widens-at-the-second-hop.warrant.json
# Markdown SHA-256:   737f2a2434e26821a3e1c7abd7de17ded43d697f8d9d3c6a69c22e20e22b4f01
# Code AST SHA-256:   8191840ad9cd3dcd7be6a48b93ca075c9430f8305b9206fd0b9dbaeb29f23b73
# Verified Classes:   WarrantContainmentError, Warrant
# Defensive Guards:   10 fail-closed invariants (zero external deps)

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


class WarrantContainmentError(RuntimeError):
    """Raised when a delegated warrant's authority exceeds its parent's."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    audience: str
    scope: FrozenSet[str]
    constraints: Mapping[str, object]
    may_subdelegate: bool
    signature_valid: bool
    link_hash_matches: bool


def derive_effective_authority(chain: Sequence[Warrant]) -> tuple[FrozenSet[str], dict]:
    if not chain:
        raise WarrantContainmentError("empty delegation chain")

    # Hop 0 is the root warrant; its scope/constraints seed the intersection.
    effective_scope = set(chain[0].scope)
    effective_constraints: dict = dict(chain[0].constraints)
    max_depth = int(effective_constraints.get("max_delegation_depth", 0))

    for i, hop in enumerate(chain):
        if not hop.signature_valid:
            raise WarrantContainmentError(f"hop {i}: bad signature from {hop.issuer}")
        if i > 0 and not hop.link_hash_matches:
            raise WarrantContainmentError(f"hop {i}: previousCredential hash mismatch")

        # Scope must narrow monotonically (semantic subset, shared interpreter).
        if not hop.scope <= effective_scope:
            widened = hop.scope - effective_scope
            raise WarrantContainmentError(
                f"hop {i}: scope widened beyond parent authority: {sorted(widened)}"
            )
        effective_scope = set(hop.scope)

        # Constraints are conjunctive: a child may only tighten, never relax.
        for key, parent_val in effective_constraints.items():
            child_val = hop.constraints.get(key)
            if child_val is None:
                raise WarrantContainmentError(
                    f"hop {i}: dropped inherited constraint '{key}'"
                )
            if key == "max_delegation_depth" and int(child_val) > int(parent_val):
                raise WarrantContainmentError(
                    f"hop {i}: relaxed max_delegation_depth {parent_val}->{child_val}"
                )
        effective_constraints.update(hop.constraints)

        # Every non-leaf hop must be permitted to delegate at all.
        if i < len(chain) - 1 and not hop.may_subdelegate:
            raise WarrantContainmentError(
                f"hop {i}: issuer {hop.issuer} lacks may_subdelegate but chain continues"
            )

    if len(chain) - 1 > max_depth:
        raise WarrantContainmentError(
            f"chain depth {len(chain) - 1} exceeds max_delegation_depth {max_depth}"
        )

    return frozenset(effective_scope), effective_constraints


def authorize(chain: Sequence[Warrant], requested: str, caller_did: str) -> bool:
    effective_scope, _ = derive_effective_authority(chain)
    leaf = chain[-1]
    if leaf.audience != caller_did:
        raise WarrantContainmentError(
            f"leaf audience {leaf.audience} is not caller {caller_did}"
        )
    if requested not in effective_scope:
        raise WarrantContainmentError(
            f"requested capability {requested!r} outside effective authority"
        )
    return True
