# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-attested-capability-when-the-a2a-v1-0-agent-card-signature-chain-is-valid-but-the-warrant-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-attested-capability-when-the-a2a-v1-0-agent-card-signature-chain-is-valid-but-the-warrant-scope.warrant.json
# Markdown SHA-256:   5d51af9deee4ca086b9bbdb1e7a63091552d38197f47b8711f2e1c7b81abcb28
# Code AST SHA-256:   a68904b66b73abaeb65ab0441da19374345a0719f80be76318c546fb67e90f7c
# Verified Classes:   WarrantScopeViolation, UnevaluableScopeError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class WarrantScopeViolation(RuntimeError):
    """Raised when a requested resource is inside an ancestor's scope but
    outside the leaf warrant's narrowed scope — the ancestor-permitted,
    leaf-forbidden boundary that name-only capability checks silently admit."""
    pass


class UnevaluableScopeError(RuntimeError):
    """Raised when the leaf warrant declares a predicate scope the callee
    cannot evaluate; fail closed rather than treat as unrestricted."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    delegate: str
    capability: str
    scope_type: str            # "path_prefix" | "resource_set" | "predicate"
    scope_value: object        # str | frozenset[str] | opaque id
    parent_hash: Optional[str] = None
    signature: str = ""

    def canonical_hash(self) -> str:
        body = f"{self.issuer}|{self.delegate}|{self.capability}|" \
               f"{self.scope_type}|{self.scope_value}|{self.parent_hash}"
        return hashlib.sha256(body.encode()).hexdigest()


def _scope_contains(w: Warrant, resource: str, evaluator) -> bool:
    if w.scope_type == "path_prefix":
        return resource.startswith(str(w.scope_value))
    if w.scope_type == "resource_set":
        return resource in w.scope_value
    if w.scope_type == "predicate":
        if evaluator is None:
            raise UnevaluableScopeError(
                f"leaf warrant {w.canonical_hash()[:12]} declares predicate "
                f"scope but no evaluator is available; refusing to fail open"
            )
        return evaluator(w.scope_value, resource)
    raise WarrantScopeViolation(f"unknown scope_type {w.scope_type!r}")


def authorize(chain: list[Warrant], resource: str, presenter_pubkey: str,
              trusted_root_issuer: str, evaluator=None) -> bool:
    if not chain:
        raise WarrantScopeViolation("empty warrant chain")

    leaf = chain[0]
    # Bind leaf to the presenting agent: possession is not authority.
    if leaf.delegate != presenter_pubkey:
        raise WarrantScopeViolation(
            f"leaf delegate {leaf.delegate!r} != presenter {presenter_pubkey!r}: "
            f"bearer replay of a detached warrant"
        )

    # Reconstruct chain to a trusted root; each child's parent_hash must
    # match the next ancestor's canonical hash.
    for i in range(len(chain) - 1):
        child, parent = chain[i], chain[i + 1]
        if child.parent_hash != parent.canonical_hash():
            raise WarrantScopeViolation(
                f"broken hash link at depth {i}: leaf detached from chain"
            )
    if chain[-1].issuer != trusted_root_issuer:
        raise WarrantScopeViolation(
            f"chain root {chain[-1].issuer!r} is not trusted"
        )

    # The invariant: evaluate against the INTERSECTION of every scope,
    # not the leaf alone. This is what name-only checks erase.
    for w in chain:
        if w.capability != leaf.capability:
            raise WarrantScopeViolation("capability drift across chain")

    if not _scope_contains(leaf, resource, evaluator):
        # Distinguish the boundary case: ancestor permitted, leaf forbidden.
        ancestor_permits = any(
            _scope_contains(w, resource, evaluator) for w in chain[1:]
        )
        if ancestor_permits:
            raise WarrantScopeViolation(
                f"resource {resource!r} is inside an ancestor warrant's scope "
                f"but outside leaf {leaf.canonical_hash()[:12]}'s narrowed "
                f"scope {leaf.scope_value!r}: narrowing gap, reject"
            )
        return False  # plain out-of-scope; caller returns 403, no raise
    return True
