#!/bin/bash
# Hook: Generate tests after code changes
# Triggers: After Edit or Write tool usage
# Purpose: Automatically request Claude to write tests for new features

set -euo pipefail

# Read hook input from stdin
INPUT=$(cat)

# Parse JSON to extract tool info
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // "unknown"')
FILE_PATH=$(echo "$INPUT" | jq -r '.input.file_path // .input.notebook_path // "unknown"')
HOOK_EVENT=$(echo "$INPUT" | jq -r '.hook_event_name // "unknown"')

# Only proceed if we have a valid file path
if [[ "$FILE_PATH" == "unknown" || "$FILE_PATH" == "null" ]]; then
  exit 0
fi

# Skip if file is in test directory (avoid recursion)
if [[ "$FILE_PATH" == *"__tests__"* || "$FILE_PATH" == *"tests/"* || "$FILE_PATH" == *".test."* || "$FILE_PATH" == *".spec."* ]]; then
  exit 0
fi

# Skip if file is configuration, documentation, or non-code
if [[ "$FILE_PATH" == *".md" || "$FILE_PATH" == *".json" || "$FILE_PATH" == *".yml" || "$FILE_PATH" == *".yaml" || "$FILE_PATH" == *".env"* || "$FILE_PATH" == *".config."* ]]; then
  exit 0
fi

# Only proceed for TypeScript/JavaScript/React files
if [[ ! "$FILE_PATH" =~ \.(ts|tsx|js|jsx)$ ]]; then
  exit 0
fi

# Create a marker file to track that tests need to be generated
MARKER_FILE="/tmp/claude_code_needs_tests_${RANDOM}.marker"
echo "$FILE_PATH" > "$MARKER_FILE"

# Output structured JSON response requesting test generation
cat <<EOF
{
  "continue": true,
  "systemMessage": "📝 Code change detected in $FILE_PATH. Tests should be generated to ensure reliability.",
  "hookSpecificOutput": {
    "hookEventName": "$HOOK_EVENT",
    "requestTestGeneration": true,
    "targetFile": "$FILE_PATH",
    "markerFile": "$MARKER_FILE"
  }
}
EOF

# Exit successfully
exit 0
