#!/usr/bin/env bash
set -euo pipefail

# Usage:
#   ./scripts/extract-module-files.sh MODULE [OUTPUT_DIR]
# Example:
#   ./scripts/extract-module-files.sh qerrors extracted

MODULE="${1:-}"
OUTDIR="${2:-extracted}"
RG="rg" # ripgrep preferred

if [[ -z "$MODULE" ]]; then
  echo "Usage: $0 MODULE [OUTPUT_DIR]"
  exit 2
fi

mkdir -p "$OUTDIR"

echo "Searching for occurrences of '$MODULE' (excluding node_modules)..."

# 1) list files that contain MODULE
if command -v "$RG" >/dev/null 2>&1; then
  FILES=$($RG -n --hidden --glob '!node_modules' -l "$MODULE" || true)
else
  FILES=$(git grep -n --no-color "$MODULE" || true)
fi

if [[ -z "$FILES" ]]; then
  echo "No files found mentioning $MODULE"
  exit 0
fi

echo "Found files:"
echo "$FILES"

# 2) Save file list
echo "$FILES" | sort -u > "$OUTDIR"/files_with_module.txt

# 3) For each file, extract matching contexts (3 lines of context)
echo "Extracting context-limited snippets..."
for f in $(echo "$FILES" | sort -u); do
  safe_name=$(echo "$f" | tr '/' '__' | sed 's/[^A-Za-z0-9_.-]/_/g')
  out="$OUTDIR/$safe_name.snippet"
  echo "===== $f =====" > "$out"
  if command -v "$RG" >/dev/null 2>&1; then
    $RG -n --hidden --glob '!node_modules' -C 3 "$MODULE" "$f" >> "$out" || true
  else
    git grep -n -C 3 "$MODULE" "$f" >> "$out" || true
  fi
  echo "" >> "$out"
done

# 4) Create summary
echo "Creating summary..."
cat > "$OUTDIR/extraction_summary.txt" << EOF
Module Extraction Summary
========================
Module: $MODULE
Date: $(date)
Files found: $(echo "$FILES" | wc -l)
Output directory: $OUTDIR

Files containing '$MODULE':
$(echo "$FILES" | sort -u)

Usage patterns detected:
- Import statements
- Configuration references  
- Function calls
- Type definitions

Review .snippet files for detailed context around each occurrence.
EOF

echo "Extraction complete. Results in: $OUTDIR/"
echo "- files_with_module.txt: List of files containing the module"
echo "- *.snippet: Code snippets with 3 lines of context"
echo "- extraction_summary.txt: Overview of findings"