#!/bin/bash

# Enhanced SCSS → LESS sync helper

echo "==================================="
echo "SCSS → LESS Sync Helper"
echo "==================================="
echo ""

# Find modified files (both staged and unstaged)
SCSS_FILES=$(git diff --name-only HEAD | grep '\.scss$' || true)
SCSS_STAGED=$(git diff --cached --name-only | grep '\.scss$' || true)
LESS_FILES=$(git diff --name-only HEAD | grep '\.less$' || true)
LESS_STAGED=$(git diff --cached --name-only | grep '\.less$' || true)
ALL_SCSS=$(printf "%s\n%s" "$SCSS_FILES" "$SCSS_STAGED" | sort -u | grep -v '^$' || true)
ALL_LESS=$(printf "%s\n%s" "$LESS_FILES" "$LESS_STAGED" | sort -u | grep -v '^$' || true)

# Count non-empty lines
if [ -z "$ALL_SCSS" ]; then
  SCSS_COUNT=0
else
  SCSS_COUNT=$(echo "$ALL_SCSS" | wc -l | tr -d ' ')
fi

if [ "$SCSS_COUNT" -eq 0 ]; then
  echo "✅ No SCSS files modified - no sync needed!"
  exit 0
fi

echo "Found $SCSS_COUNT modified SCSS file(s):"
echo ""

NEEDS_SYNC=0

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

  # Strip packages/style/ prefix if present
  RELATIVE_FILE="${file#packages/style/}"
  LESS_FILE="${RELATIVE_FILE%.scss}.less"

  if [ -f "$LESS_FILE" ]; then
    # Check if LESS file also modified
    LESS_FULL_PATH="${file%.scss}.less"
    if echo "$ALL_LESS" | grep -q "^${LESS_FULL_PATH}$"; then
      echo "  ✅ $RELATIVE_FILE (LESS already updated)"
    else
      echo "  ⚠️  $RELATIVE_FILE → $LESS_FILE (NEEDS SYNC)"
      NEEDS_SYNC=1
    fi
  else
    echo "  ⚠️  $RELATIVE_FILE (no corresponding LESS file)"
  fi
done <<< "$ALL_SCSS"

if [ $NEEDS_SYNC -eq 1 ]; then
  echo ""
  echo "==================================="
  echo "⚠️  LESS files need syncing!"
  echo "==================================="
  echo ""
  echo "Options:"
  echo "1. Semi-automated: ./helper-scripts/convert-scss-to-less.sh --all"
  echo "2. Single file:    ./helper-scripts/convert-scss-to-less.sh path/to/file.scss"
  echo "3. Manually sync SCSS → LESS"
  echo "4. Ask Claude to sync for you"
  echo ""
  exit 1
fi

echo ""
echo "✅ All LESS files are in sync!"
exit 0
