#!/bin/bash

# Kill any existing processes on port 3001
echo "Killing any existing processes on port 3001..."
lsof -i :3001 | grep LISTEN | awk '{print $2}' | xargs kill -9 2>/dev/null || true

# 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

# Start a simple HTTP server
echo "🚀 Starting HTTP server..."
python3 -m http.server 8080 &
HTTP_PID=$!

# Function to handle script termination
cleanup() {
  echo "🛑 Stopping all processes..."
  kill $SERVER_PID $HTTP_PID 2>/dev/null || true
  exit 0
}

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

echo "✅ All services started!"
echo "📝 Demo: http://localhost:8080/demo.html"
echo "📡 Backend server: http://localhost:3001"
echo "Press Ctrl+C to stop all services"

# Keep the script running
wait