#!/usr/bin/env bash

# Generate extras metadata from LazyVim repository
# This script scans the LazyVim extras directory and creates extras.nix

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TEMP_DIR=$(mktemp -d)
EXTRAS_OUTPUT="$PROJECT_ROOT/extras.nix"

cleanup() {
  rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

echo "Cloning LazyVim repository..."
git clone --depth 1 --filter=blob:none --sparse https://github.com/LazyVim/LazyVim "$TEMP_DIR/LazyVim" 2>/dev/null
cd "$TEMP_DIR/LazyVim"
git sparse-checkout set lua/lazyvim/plugins/extras 2>/dev/null

EXTRAS_DIR="$TEMP_DIR/LazyVim/lua/lazyvim/plugins/extras"

if [ ! -d "$EXTRAS_DIR" ]; then
  echo "Error: Extras directory not found"
  exit 1
fi

echo "Generating extras metadata..."

# Start building the Nix file
cat > "$EXTRAS_OUTPUT" << 'EOF'
# Auto-generated extras metadata from LazyVim
# Generated by scripts/generate-extras-metadata.sh
# DO NOT EDIT MANUALLY

{
EOF

# Process each category directory
for category_dir in "$EXTRAS_DIR"/*; do
  if [ ! -d "$category_dir" ]; then
    continue
  fi

  category=$(basename "$category_dir")

  # Skip vscode.lua (it's a file, not a directory)
  if [ "$category" = "vscode.lua" ]; then
    continue
  fi

  echo "  $category = {" >> "$EXTRAS_OUTPUT"

  # Process each extra file in the category
  for extra_file in "$category_dir"/*.lua; do
    if [ ! -f "$extra_file" ]; then
      continue
    fi

    extra_name=$(basename "$extra_file" .lua)
    # Convert hyphens to underscores for Nix attribute names
    nix_name=$(echo "$extra_name" | sed 's/-/_/g')
    import_path="lazyvim.plugins.extras.$category.$extra_name"

    echo "    \"$nix_name\" = {" >> "$EXTRAS_OUTPUT"
    echo "      name = \"$extra_name\";" >> "$EXTRAS_OUTPUT"
    echo "      category = \"$category\";" >> "$EXTRAS_OUTPUT"
    echo "      import = \"$import_path\";" >> "$EXTRAS_OUTPUT"
    echo "    };" >> "$EXTRAS_OUTPUT"
  done

  echo "  };" >> "$EXTRAS_OUTPUT"
done

# Close the Nix attrset
echo "}" >> "$EXTRAS_OUTPUT"

echo "Extras metadata generated at $EXTRAS_OUTPUT"

# Count total extras
total_extras=$(grep -c 'import = ' "$EXTRAS_OUTPUT" || true)
echo "Total extras found: $total_extras"
