#!/bin/bash
# Hook: Restructure code after tests are created
# Triggers: After Edit or Write tool usage in test files
# Purpose: Request Claude to refactor code with better documentation and structure

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

# Only proceed if this is a test file
if [[ ! "$FILE_PATH" == *"__tests__"* && ! "$FILE_PATH" == *"tests/"* && ! "$FILE_PATH" == *".test."* && ! "$FILE_PATH" == *".spec."* ]]; then
  exit 0
fi

# Check if there's a corresponding source file to restructure
# Convert test file path to source file path
SOURCE_FILE=""

if [[ "$FILE_PATH" == *"__tests__/"* ]]; then
  # Pattern: __tests__/path/to/file.test.ts -> path/to/file.ts
  SOURCE_FILE=$(echo "$FILE_PATH" | sed 's|__tests__/||' | sed 's|\.test\.||' | sed 's|\.spec\.||')
elif [[ "$FILE_PATH" == *"/tests/"* ]]; then
  # Pattern: tests/path/to/file.spec.ts -> app/path/to/file.ts or lib/path/to/file.ts
  RELATIVE_PATH=$(echo "$FILE_PATH" | sed 's|.*/tests/||' | sed 's|\.test\.||' | sed 's|\.spec\.||')

  # Try multiple common source locations
  if [[ -f "mawidi-site/app/$RELATIVE_PATH" ]]; then
    SOURCE_FILE="mawidi-site/app/$RELATIVE_PATH"
  elif [[ -f "mawidi-site/lib/$RELATIVE_PATH" ]]; then
    SOURCE_FILE="mawidi-site/lib/$RELATIVE_PATH"
  elif [[ -f "mawidi-site/components/$RELATIVE_PATH" ]]; then
    SOURCE_FILE="mawidi-site/components/$RELATIVE_PATH"
  fi
fi

# If we found a source file, request restructuring
if [[ -n "$SOURCE_FILE" && -f "$SOURCE_FILE" ]]; then
  cat <<EOF
{
  "continue": true,
  "systemMessage": "✅ Tests created for $SOURCE_FILE. Code can now be safely restructured and documented.",
  "hookSpecificOutput": {
    "hookEventName": "$HOOK_EVENT",
    "requestRestructuring": true,
    "sourceFile": "$SOURCE_FILE",
    "testFile": "$FILE_PATH"
  }
}
EOF
else
  # No source file found, just continue
  cat <<EOF
{
  "continue": true,
  "suppressOutput": true
}
EOF
fi

exit 0
