# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-authorization-decision-as-bound-to-the-argument-bytes-it-was-issued-against-rather-than-to-the-too.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-authorization-decision-as-bound-to-the-argument-bytes-it-was-issued-against-rather-than-to-the-too.warrant.json
# Markdown SHA-256:   628f11e538f0f2454762964c2ce03e41b0cd304b61a3585cd55a63003e909136
# Code AST SHA-256:   38d388352173472b5b5ee073183a9e53ba90cdeabfc5f7ee487c9fadfe973a86
# Verified Classes:   ArgumentBindingError, AuthToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
import os
from dataclasses import dataclass


class ArgumentBindingError(RuntimeError):
    """Raised when a dispatch attempts to use an authorization token whose
    argument hash does not match the bytes being dispatched, or when the
    canonicalization used at authorization differs from dispatch."""


def canonicalize(tool_name: str, args: dict) -> bytes:
    """Single canonical form used by BOTH the policy engine and the dispatcher.
    Paths are normalized with realpath-equivalent semantics so that
    '/workspace/../etc' and '/etc' cannot hash differently while resolving
    to the same filesystem object."""
    normalized = {}
    for key, value in args.items():
        if key in ("path", "file", "target") and isinstance(value, str):
            normalized[key] = os.path.realpath(value)
        elif isinstance(value, str):
            normalized[key] = value
        else:
            normalized[key] = value
    payload = {"tool": tool_name, "args": normalized}
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def arg_hash(tool_name: str, args: dict) -> str:
    return hashlib.sha256(canonicalize(tool_name, args)).hexdigest()


@dataclass(frozen=True)
class AuthToken:
    tool: str
    session: str
    args_hash: str
    ttl_expires_at: float


def dispatch(token: AuthToken, tool_name: str, args: dict, now: float) -> None:
    if token.tool != tool_name:
        raise ArgumentBindingError(
            f"token bound to tool {token.tool!r}, dispatch requested {tool_name!r}"
        )
    if now >= token.ttl_expires_at:
        raise ArgumentBindingError(f"token for {tool_name!r} expired")
    actual = arg_hash(tool_name, args)
    if actual != token.args_hash:
        raise ArgumentBindingError(
            f"argument hash mismatch for {tool_name!r}: token bound to "
            f"{token.args_hash[:12]}, dispatch presents {actual[:12]} — "
            f"re-enter policy engine, do not dispatch"
        )
    # Only here is the side effect performed.
    _perform(tool_name, args)


def _perform(tool_name: str, args: dict) -> None:
    pass
