#!/bin/bash

echo "🚀 Quick Start - AI Wireframe Generator"
echo "======================================"
echo

echo "📋 Checking prerequisites..."
echo

# Check if Python is installed
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 is not installed or not in PATH"
    echo "Please install Python 3.8+ and try again"
    exit 1
fi

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed or not in PATH"
    echo "Please install Node.js 18+ and try again"
    exit 1
fi

echo "✅ Python and Node.js are installed"
echo

echo "🔧 Setting up backend..."
cd backend

# Check if .env exists
if [ ! -f .env ]; then
    echo "📝 Creating .env file..."
    cp env.example .env
    echo "⚠️  Please edit .env and add your Claude API key"
    echo "   Then restart this script"
    exit 1
fi

# Check if requirements are installed
if ! python3 -c "import flask" &> /dev/null; then
    echo "📦 Installing Python dependencies..."
    pip3 install -r requirements.txt
    if [ $? -ne 0 ]; then
        echo "❌ Failed to install dependencies"
        exit 1
    fi
fi

echo "✅ Backend setup complete"
echo

echo "🚀 Starting backend in background..."
python3 run.py &
BACKEND_PID=$!

echo "⏳ Waiting for backend to start..."
sleep 5

echo "🌐 Backend should be running on http://localhost:5000"
echo

echo "🚀 Starting frontend..."
cd ..
npm run dev &
FRONTEND_PID=$!

echo
echo "🎉 Both services are starting!"
echo
echo "📱 Frontend: http://localhost:3000"
echo "🔧 Backend: http://localhost:5000"
echo
echo "💡 Tips:"
echo "   - Wait for both services to fully start"
echo "   - Check the right sidebar for backend status"
echo "   - Try generating a wireframe with AI"
echo

# Function to cleanup background processes
cleanup() {
    echo
    echo "🛑 Stopping services..."
    kill $BACKEND_PID 2>/dev/null
    kill $FRONTEND_PID 2>/dev/null
    echo "✅ Services stopped"
    exit 0
}

# Set trap to cleanup on script exit
trap cleanup SIGINT SIGTERM

echo "Press Ctrl+C to stop both services"
echo

# Wait for user to stop
wait
