# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-it-cannot-re-derive-the-depth-truncated-delegation-chain-in-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-warrant-it-cannot-re-derive-the-depth-truncated-delegation-chain-in-aaif.warrant.json
# Markdown SHA-256:   b9df769dc09520f01ab5469e793ad89b349159d4ed3a75e34363eab32c6ec054
# Code AST SHA-256:   47b8894b43d8d8a3f5d4fd872e5cb2c5a01c7b945947385adc7d9c47223f8d21
# Verified Classes:   WarrantUnderivedError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantUnderivedError(RuntimeError):
    """Raised when a delegated warrant cannot be re-derived from a full,
    monotonic, root-anchored chain resident in the instance's context."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    signature: str  # per-link signature; authentic iff issuer signed it


def _chain_hash(chain: list[Warrant]) -> str:
    h = hashlib.sha256()
    for w in chain:
        h.update(f"{w.issuer}|{w.subject}|{sorted(w.scope)}|{w.signature}".encode())
    return h.hexdigest()


def verify_and_authorize(
    leaf: Warrant,
    presented_chain: list[Warrant],
    trusted_roots: set[str],
    requested_scope: frozenset,
    checkpoint_chain_hash: Optional[str] = None,
) -> str:
    """Act only if the full chain is resident, monotonic, and root-anchored.

    Refuse-and-halt on any under-derivation. Never synthesize missing links
    from a provenance hint.
    """
    # (1) Full chain must be resident: leaf must be the terminal element.
    if not presented_chain or presented_chain[-1] != leaf:
        raise WarrantUnderivedError(
            f"leaf warrant {leaf.subject} not terminal in presented chain; "
            f"chain length {len(presented_chain)} — refuse, do not infer"
        )

    # (2) Root must be independently trusted, not named by a hint.
    root = presented_chain[0]
    if root.issuer not in trusted_roots:
        raise WarrantUnderivedError(
            f"chain root issuer {root.issuer!r} not in trusted anchors; "
            f"provenance hint is a claim, not a warrant"
        )

    # (3) Scope monotonicity across every adjacent pair.
    for parent, child in zip(presented_chain, presented_chain[1:]):
        if not parent.scope.issuperset(child.scope):
            raise WarrantUnderivedError(
                f"scope escalation at link {parent.subject}->{child.subject}: "
                f"{sorted(child.scope - parent.scope)} not held by parent"
            )

    # (4) Checkpoint binding: resumed instances must re-derive the same chain.
    if checkpoint_chain_hash is not None:
        if _chain_hash(presented_chain) != checkpoint_chain_hash:
            raise WarrantUnderivedError(
                "chain hash mismatch against checkpoint; possible truncation "
                "or mid-chain substitution across resume"
            )

    # (5) Requested scope must be covered by the leaf.
    if not leaf.scope.issuperset(requested_scope):
        raise WarrantUnderivedError(
            f"requested scope {sorted(requested_scope - leaf.scope)} not "
            f"delegated to {leaf.subject}"
        )

    return _chain_hash(presented_chain)
