#!/bin/bash
# PostToolUse hook: Refresh codebase map after source files are modified
# Triggers on Write/Edit of source files (.ts/.tsx/.js/.jsx/.py/.rs)
# Runs codebase-map.py in background so it doesn't block the agent
# NOTE: This script needs chmod +x to be executable
#
# This hook requires a codebase-map.py script. If you don't have one,
# you can safely remove this hook from settings.json.

PROJECT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"

# Read the tool input from stdin to get the modified file path
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',{}).get('file_path',''))" 2>/dev/null)

# Only refresh for source code files (not markdown, JSON, etc.)
case "$FILE_PATH" in
    *.ts|*.tsx|*.js|*.jsx|*.py|*.rs|*.go|*.java|*.rb|*.swift|*.kt)
        # Check if codebase-map.py exists
        if [ -f "$PROJECT_DIR/codebase-map.py" ]; then
            python3 "$PROJECT_DIR/codebase-map.py" > /dev/null 2>&1 &
        elif [ -f "$PROJECT_DIR/scripts/codebase-map.py" ]; then
            python3 "$PROJECT_DIR/scripts/codebase-map.py" > /dev/null 2>&1 &
        fi
        ;;
esac

exit 0
