# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-aaif-delegation-chain-is-scope-valid-yet-authority-inert-at-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-aaif-delegation-chain-is-scope-valid-yet-authority-inert-at-tool-invocation.warrant.json
# Markdown SHA-256:   1cb5afd37fa321ebbb9b2bd9ad599c34a24cb0bcec0cf2d8a83a5876060d9a8a
# Code AST SHA-256:   c298445b8ba3701b068d1b3b2a1a22f939744265f28e0ab912278963dba1d9e5
# Verified Classes:   AuthorityInertError, ChainInvalidError, Constraint, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable


class AuthorityInertError(RuntimeError):
    """Chain is cryptographically valid but carries no effective authority for this invocation."""
    pass


class ChainInvalidError(RuntimeError):
    """Signature, DID, or per-hop subset validation failed."""
    pass


@dataclass(frozen=True)
class Constraint:
    field: str
    predicate: Callable[[object], bool]
    label: str


@dataclass(frozen=True)
class Hop:
    constraints: tuple[Constraint, ...]


def project_intersection(chain: list[Hop], invocation: dict, tool_domain: dict) -> None:
    """Evaluate the conjunction of all hop constraints on the concrete invocation.

    Raises ChainInvalidError if any hop is individually malformed (caller should
    have run subset validation already; this is a guard).
    Raises AuthorityInertError if the intersection is empty on the tool domain
    or does not contain the invocation tuple.
    """
    if not chain:
        raise ChainInvalidError("empty delegation chain")

    for field in invocation:
        if field not in tool_domain:
            raise ChainInvalidError(f"invocation field {field!r} outside tool domain")

    # Collect every constraint across every hop; conjunction, not per-hop.
    active: list[Constraint] = [c for hop in chain for c in hop.constraints]

    for c in active:
        if c.field not in invocation:
            # A constraint on a field the tool never receives is inert by itself,
            # but its presence signals a schema mismatch, not silent success.
            raise AuthorityInertError(
                f"constraint {c.label!r} references field {c.field!r} "
                f"absent from invocation; cannot evaluate effective authority"
            )
        if not c.predicate(invocation[c.field]):
            raise AuthorityInertError(
                f"invocation violates constraint {c.label!r} on {c.field!r}; "
                f"chain is valid but authority-inert for this call"
            )

    # Explicit emptiness witness: find any two constraints on the same field
    # whose joint satisfaction is impossible on the tool's discrete domain.
    by_field: dict[str, list[Constraint]] = {}
    for c in active:
        by_field.setdefault(c.field, []).append(c)

    for field, cs in by_field.items():
        if len(cs) < 2:
            continue
        domain_values = tool_domain[field]
        satisfiable = [
            v for v in domain_values if all(c.predicate(v) for c in cs)
        ]
        if not satisfiable:
            labels = " AND ".join(c.label for c in cs)
            raise AuthorityInertError(
                f"empty intersection on {field!r}: [{labels}] "
                f"has no satisfiable value in tool domain {domain_values!r}"
            )


def authorize_tool_call(
    chain: list[Hop],
    invocation: dict,
    tool_domain: dict,
    gateway_window: tuple[int, int],
    invocation_time: int,
) -> None:
    start, end = gateway_window
    if not (start <= invocation_time < end):
        raise AuthorityInertError(
            f"invocation time {invocation_time} outside gateway window "
            f"[{start}, {end}); chain temporally inert"
        )
    project_intersection(chain, invocation, tool_domain)
