#!/bin/bash

# SMTP API Service Startup Script
# هذا السكريبت يقوم بتشغيل Backend وFrontend معاً

echo "🚀 Starting SMTP API Service..."
echo ""

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Check if Python is installed
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 is not installed. Please install Python 3.8 or higher."
    exit 1
fi

# Install Python dependencies if needed
echo "📦 Checking Python dependencies..."
pip install -q fastapi uvicorn sqlalchemy pydantic-settings python-jose passlib python-multipart email-validator 2>/dev/null

# Start Backend
echo "${BLUE}🔧 Starting Backend Server...${NC}"
cd backend
python main.py &
BACKEND_PID=$!
cd ..

# Wait for backend to start
sleep 3

echo "${GREEN}✅ Backend running at http://localhost:8000${NC}"
echo "${GREEN}📚 API Docs at http://localhost:8000/docs${NC}"
echo ""

# Start Frontend
echo "${BLUE}🎨 Starting Frontend Server...${NC}"
cd frontend
python3 -m http.server 5173 &
FRONTEND_PID=$!
cd ..

sleep 2

echo "${GREEN}✅ Frontend running at http://localhost:5173${NC}"
echo ""
echo "${GREEN}🎉 SMTP API Service is ready!${NC}"
echo ""
echo "Press Ctrl+C to stop both servers"
echo ""

# Function to cleanup on exit
cleanup() {
    echo ""
    echo "🛑 Stopping servers..."
    kill $BACKEND_PID 2>/dev/null
    kill $FRONTEND_PID 2>/dev/null
    echo "✅ Servers stopped"
    exit 0
}

# Trap Ctrl+C
trap cleanup INT

# Keep script running
wait
