# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-chained-mcp-tool-manifest-when-the-trust-anchor-path-exceeds-its-declared-delegation-depth-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-chained-mcp-tool-manifest-when-the-trust-anchor-path-exceeds-its-declared-delegation-depth-mid-handoff.warrant.json
# Markdown SHA-256:   eac21a4795cdbb45ec22e6e248a3d99fcf9e70ad6b2f5b1be9fc3dcaf3ad616b
# Code AST SHA-256:   f68f4fe54a28899e23646d02cd2776172a9f11335d64a5b065d5c04d683732b3
# Verified Classes:   DelegationDepthExhausted, ManifestMutationDetected, LeafIssuerMismatch, Grant, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationDepthExhausted(RuntimeError):
    """Raised when a signed MCP manifest's chain consumes more delegation
    depth than the trust anchor granted, even though every signature in
    the chain verifies cryptographically."""


class ManifestMutationDetected(RuntimeError):
    """Raised when the manifest content hash changed mid-task after the
    agent had pinned and verified an earlier chain."""


class LeafIssuerMismatch(RuntimeError):
    """Raised when the manifest body signer is not the terminal element
    of the verified signature chain."""


@dataclass(frozen=True)
class Grant:
    issuer: str
    subject: str
    remaining_depth: int  # depth budget this grant confers on subject


@dataclass(frozen=True)
class Manifest:
    leaf_issuer: str
    content_hash: str
    chain: tuple  # ordered tuple[Grant], index 0 = hop from anchor


def verify_and_authorize(
    manifest: Manifest,
    trust_anchors: frozenset,
    pinned_hash: Optional[str],
    signatures_ok: bool,
) -> str:
    # Gate 1: cryptographic signatures must all verify.
    if not signatures_ok:
        raise DelegationDepthExhausted("signature verification failed")

    # Gate 2: manifest must not have mutated since task-scoped pin.
    if pinned_hash is not None and manifest.content_hash != pinned_hash:
        raise ManifestMutationDetected(
            f"manifest hash {manifest.content_hash} != pinned {pinned_hash}"
        )

    # Gate 3: chain must originate at a local trust anchor.
    if not manifest.chain or manifest.chain[0].issuer not in trust_anchors:
        raise DelegationDepthExhausted(
            f"chain root {manifest.chain[0].issuer if manifest.chain else None} "
            f"is not a configured trust anchor"
        )

    # Gate 4: ordered fold over delegation depth. Intra-org hops are NOT free.
    depth = None
    for idx, grant in enumerate(manifest.chain):
        if idx == 0:
            depth = grant.remaining_depth
        else:
            prev = manifest.chain[idx - 1]
            if grant.issuer != prev.subject:
                raise DelegationDepthExhausted(
                    f"chain discontinuity at hop {idx}: "
                    f"{grant.issuer} != {prev.subject}"
                )
            depth -= 1  # every hop costs one unit, regardless of org
        if depth < 0:
            raise DelegationDepthExhausted(
                f"delegation depth exhausted at hop {idx} "
                f"(issuer={grant.issuer}, subject={grant.subject}); "
                f"anchor granted {manifest.chain[0].remaining_depth}"
            )

    # Gate 5: leaf identity binding.
    if manifest.leaf_issuer != manifest.chain[-1].subject:
        raise LeafIssuerMismatch(
            f"manifest signed by {manifest.leaf_issuer} but chain "
            f"terminates at {manifest.chain[-1].subject}"
        )

    return manifest.leaf_issuer
