#!/bin/bash

# Build the fixed SDK
echo "📦 Building the fixed SDK..."
cd fixed-sdk
npm install
bash manual-build.sh
cd ..

# Start the backend server
echo "🚀 Starting the backend server..."
cd api
npm install
node server.js &
SERVER_PID=$!
cd ..

# Wait for the server to start
echo "⏳ Waiting for the server to start..."
sleep 2

# Install dependencies for the React test
echo "📦 Installing dependencies for the React test..."
cd react-test

# Create a .env file to set the port to 3000
echo "PORT=3000" > .env

# Install dependencies
npm install

# Start the React test
echo "🚀 Starting the React test..."
REACT_SCRIPTS_VERSION=$(npm list react-scripts | grep react-scripts | cut -d@ -f2 | cut -d' ' -f1)
if [[ "$REACT_SCRIPTS_VERSION" == "5"* ]]; then
  # For React Scripts 5.x
  BROWSER=none npm start &
else
  # For older versions
  BROWSER=none npm start &
fi
REACT_PID=$!
cd ..

# Function to handle script termination
cleanup() {
  echo "🛑 Stopping all processes..."
  kill $SERVER_PID $REACT_PID
  exit 0
}

# Register the cleanup function for script termination
trap cleanup SIGINT SIGTERM

echo "✅ All services started!"
echo "📝 React test: http://localhost:3000"
echo "📡 Backend server: http://localhost:3001"
echo "Press Ctrl+C to stop all services"

# Keep the script running
wait