#!/bin/bash
# Hook: PreToolUse — inject tool-specific constraints
# Triggered before a tool is used
#
# Detects which tool is being used and injects relevant constraints.

set -e

# Resolve prompts dir relative to this hook's location
HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROMPTS_DIR="$HOOK_DIR/prompts/tools"

# If not found next to hook, check extension directory
if [ ! -d "$PROMPTS_DIR" ]; then
    EXTENSION_DIR="$(cd "$HOOK_DIR/.." && pwd)"
    PROMPTS_DIR="$EXTENSION_DIR/prompts/tools"
fi

if [ ! -d "$PROMPTS_DIR" ]; then
    echo '{"type": "no-op"}'
    exit 0
fi

# Read tool name from stdin (hook context JSON)
INPUT=$(cat)
TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.toolName // ""' 2>/dev/null || echo "")

CONTEXT=""

case "$TOOL_NAME" in
    edit|Edit)
        [ -f "$PROMPTS_DIR/edit-constraints.md" ] && CONTEXT=$(cat "$PROMPTS_DIR/edit-constraints.md")
        ;;
    run_shell_command|Bash|run_shell_command_with_description)
        [ -f "$PROMPTS_DIR/bash-constraints.md" ] && CONTEXT=$(cat "$PROMPTS_DIR/bash-constraints.md")
        ;;
    grep_search|Grep|glob|Glob|read_file|ReadFile)
        [ -f "$PROMPTS_DIR/search-best-practices.md" ] && CONTEXT=$(cat "$PROMPTS_DIR/search-best-practices.md")
        ;;
    *)
        # Log unknown tools for debugging (goes to Qwen log, not user output)
        echo "tool-guard: no constraints for tool '$TOOL_NAME'" >&2
        echo '{"type": "no-op"}'
        exit 0
        ;;
esac

if [ -z "$CONTEXT" ]; then
    echo '{"type": "no-op"}'
    exit 0
fi

printf '{"type": "additionalContext", "context": %s}\n' "$(printf '%s' "$CONTEXT" | jq -Rs .)"
