#!/bin/bash

# Remove redundant variable imports from LESS files
# Variables are imported at entry points (main.less, branding.less, login.less),
# so component files don't need to import them due to LESS's global scope.

set -e

cd "$(dirname "$0")/.."

echo "=============================================="
echo "Removing Redundant Variable Imports"
echo "=============================================="
echo ""
echo "LESS uses global scope, so variables imported at entry points"
echo "are available to all subsequent imports. This is different from"
echo "SCSS's @use module system which requires explicit imports."
echo ""

# Find all LESS files with variable imports (excluding entry points)
FILES=$(grep -rl '@import.*variables/index\.less' styles --include="*.less" 2>/dev/null || true)

# Exclude entry points that SHOULD keep variable imports
FILES=$(echo "$FILES" | grep -v "^styles/login-app\.less$" || true)
FILES=$(echo "$FILES" | grep -v "^styles/_login-app\.less$" || true)

if [ -z "$FILES" ]; then
  echo "✅ No redundant variable imports found!"
  exit 0
fi

COUNT=$(echo "$FILES" | wc -l | tr -d ' ')
echo "Found $COUNT file(s) with redundant variable imports:"
echo ""
echo "$FILES" | sed 's/^/  - /'
echo ""

read -p "Remove redundant imports from these files? [y/N] " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Cancelled - no changes made"
  exit 0
fi

echo ""
echo "Removing redundant variable imports..."
echo ""

UPDATED=0

while IFS= read -r file; do
  if [ -z "$file" ]; then
    continue
  fi

  # Remove variable import lines
  sed -i.bak -E '/@import[[:space:]]+.*variables\/index\.less/d' "$file"

  # Check if file changed
  if ! diff -q "$file" "$file.bak" >/dev/null 2>&1; then
    echo "  ✅ Updated: $file"
    UPDATED=$((UPDATED + 1))
    rm "$file.bak"
  else
    echo "  ⏭️  Skipped (no changes): $file"
    rm "$file.bak"
  fi
done <<< "$FILES"

echo ""
echo "=============================================="
echo "✅ Updated $UPDATED file(s)"
echo "=============================================="
echo ""
echo "Next steps:"
echo "1. Run: npm test (to verify LESS/SCSS compilation)"
echo "2. Review changes: git diff"
echo "3. Commit if all looks good"
echo ""
