# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-transitively-attested-capability-grant-in-cross-org-federation-and-how-does-trust-anchor-depth-collaps.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-transitively-attested-capability-grant-in-cross-org-federation-and-how-does-trust-anchor-depth-collaps.warrant.json
# Markdown SHA-256:   e63ef9160e98c48ecfe64f007fad62ef5f5608ed1356bc60a75ff0cc1478449e
# Code AST SHA-256:   73d9417897fc8ecd2658a08f70703bfa38ef3de20e22942b1ef9e569a9bba989
# Verified Classes:   WarrantAuthorityError, HopClaim, AnchorPolicy, EffectiveAuthority
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantAuthorityError(RuntimeError):
    """Raised when a warrant is authentic but its folded authority is insufficient."""
    pass


@dataclass
class HopClaim:
    issuer_did: str
    policy_digest: str
    max_delegation_depth: int          # restated by this hop; must not widen
    counterparty_allowlist: frozenset  # restated; must not widen
    signature_valid: bool


@dataclass
class AnchorPolicy:
    anchor_did: str
    max_delegation_depth: int
    trusted_peer_digests: frozenset
    counterparty_allowlist: frozenset


@dataclass
class EffectiveAuthority:
    remaining_depth: int
    allowlist: frozenset = field(default_factory=frozenset)


def fold_and_authorize(
    anchor: AnchorPolicy,
    chain: list[HopClaim],
    target_counterparty: str,
) -> EffectiveAuthority:
    """
    Fold a warrant chain under meet-semantics and authorize the target action.
    Rejects widening, stranger hops, and depth overrun against the ANCHOR bound.
    """
    eff = EffectiveAuthority(
        remaining_depth=anchor.max_delegation_depth,
        allowlist=anchor.counterparty_allowlist,
    )

    for idx, hop in enumerate(chain):
        if not hop.signature_valid:
            raise WarrantAuthorityError(
                f"hop {idx} ({hop.issuer_did}): signature invalid"
            )

        if hop.policy_digest not in anchor.trusted_peer_digests:
            raise WarrantAuthorityError(
                f"hop {idx} ({hop.issuer_did}): policy digest "
                f"{hop.policy_digest} not pinned by anchor {anchor.anchor_did}"
            )

        # Widening check: a hop may narrow but never exceed inherited depth.
        if hop.max_delegation_depth > eff.remaining_depth:
            raise WarrantAuthorityError(
                f"hop {idx} ({hop.issuer_did}): widening delegation depth "
                f"{hop.max_delegation_depth} > inherited {eff.remaining_depth}"
            )

        # Widening check on allowlist: hop's set must be a subset of inherited.
        if not hop.counterparty_allowlist.issubset(eff.allowlist):
            widened = hop.counterparty_allowlist - eff.allowlist
            raise WarrantAuthorityError(
                f"hop {idx} ({hop.issuer_did}): allowlist widening {sorted(widened)}"
            )

        # Meet: narrow the effective authority.
        eff.remaining_depth = min(eff.remaining_depth, hop.max_delegation_depth) - 1
        eff.allowlist = eff.allowlist & hop.counterparty_allowlist

        if eff.remaining_depth < 0:
            raise WarrantAuthorityError(
                f"hop {idx} ({hop.issuer_did}): cumulative depth exceeds "
                f"anchor bound {anchor.max_delegation_depth}"
            )

    if target_counterparty not in eff.allowlist:
        raise WarrantAuthorityError(
            f"target {target_counterparty} not in folded allowlist "
            f"{sorted(eff.allowlist)}"
        )

    return eff
