#!/bin/bash

# Check if a project path is provided
if [ -z "$1" ]; then
  echo "❌ Error: Please provide a path to your React project"
  echo "Usage: ./migrate-project.sh /path/to/your/react-project"
  exit 1
fi

REACT_PROJECT_PATH="$1"

# Check if the project path exists
if [ ! -d "$REACT_PROJECT_PATH" ]; then
  echo "❌ Error: The provided path does not exist or is not a directory"
  exit 1
fi

# Check if it's a React project (has package.json with react dependency)
if [ ! -f "$REACT_PROJECT_PATH/package.json" ]; then
  echo "❌ Error: The provided path does not contain a package.json file"
  exit 1
fi

echo "🔍 Checking for old RealtimeCursor SDK..."
if grep -q "realtimecursor-sdk" "$REACT_PROJECT_PATH/package.json"; then
  echo "✅ Found old RealtimeCursor SDK"
  
  # Check if using npm or yarn
  if [ -f "$REACT_PROJECT_PATH/yarn.lock" ]; then
    echo "📦 Using yarn to update dependencies..."
    cd "$REACT_PROJECT_PATH"
    yarn remove realtimecursor-sdk
    yarn add realtimecursor-sdk-fixed
  else
    echo "📦 Using npm to update dependencies..."
    cd "$REACT_PROJECT_PATH"
    npm uninstall realtimecursor-sdk
    npm install realtimecursor-sdk-fixed
  fi
  
  echo "🔍 Updating imports in source files..."
  find "$REACT_PROJECT_PATH/src" -type f -name "*.js" -o -name "*.jsx" -o -name "*.ts" -o -name "*.tsx" | xargs sed -i 's/from "realtimecursor-sdk"/from "realtimecursor-sdk-fixed"/g'
  find "$REACT_PROJECT_PATH/src" -type f -name "*.js" -o -name "*.jsx" -o -name "*.ts" -o -name "*.tsx" | xargs sed -i "s/from 'realtimecursor-sdk'/from 'realtimecursor-sdk-fixed'/g"
  
  echo "📝 Adding CSS import to main file..."
  MAIN_FILE=""
  if [ -f "$REACT_PROJECT_PATH/src/index.js" ]; then
    MAIN_FILE="$REACT_PROJECT_PATH/src/index.js"
  elif [ -f "$REACT_PROJECT_PATH/src/index.jsx" ]; then
    MAIN_FILE="$REACT_PROJECT_PATH/src/index.jsx"
  elif [ -f "$REACT_PROJECT_PATH/src/index.ts" ]; then
    MAIN_FILE="$REACT_PROJECT_PATH/src/index.ts"
  elif [ -f "$REACT_PROJECT_PATH/src/index.tsx" ]; then
    MAIN_FILE="$REACT_PROJECT_PATH/src/index.tsx"
  fi
  
  if [ ! -z "$MAIN_FILE" ]; then
    if ! grep -q "realtimecursor-sdk-fixed/dist/cursor.css" "$MAIN_FILE"; then
      echo "import 'realtimecursor-sdk-fixed/dist/cursor.css';" >> "$MAIN_FILE"
    fi
  fi
  
  echo "✅ Migration completed successfully!"
  echo "📝 Please check the UPGRADE.md file for more information on using the new components."
else
  echo "❌ RealtimeCursor SDK not found in the project"
  echo "📝 You can install it with:"
  echo "   npm install realtimecursor-sdk-fixed"
  echo "   # or"
  echo "   yarn add realtimecursor-sdk-fixed"
fi