#!/bin/bash

# Grateful Journal - Start All Services
# Runs MongoDB, FastAPI backend, and Vite frontend in one command

set -e

# Cleanup on Ctrl+C or exit
cleanup() {
    echo ""
    echo "Stopping all services..."
    kill $BACKEND_PID $FRONTEND_PID 2>/dev/null || true
    wait $BACKEND_PID $FRONTEND_PID 2>/dev/null || true
    echo "All services stopped."
    exit 0
}
trap cleanup INT TERM

echo "Starting Grateful Journal..."
echo ""

# Check if MongoDB is running
echo "Checking MongoDB..."
if lsof -Pi :27017 -sTCP:LISTEN -t >/dev/null 2>&1 ; then
    echo "MongoDB already running on port 27017"
else
    echo "Starting MongoDB..."
    brew services start mongodb-community
    sleep 2
    echo "MongoDB started on port 27017"
fi

echo ""

# Start Backend (FastAPI with conda environment)
echo "Starting FastAPI backend..."
conda run -n yoyo python backend/main.py &
BACKEND_PID=$!
echo "Backend running on http://localhost:8001 (PID: $BACKEND_PID)"

sleep 2

echo ""

# Start Frontend (Vite)
echo "Starting Vite frontend..."
npm run dev -- --port 8000 &
FRONTEND_PID=$!
echo "Frontend running on http://localhost:8000 (PID: $FRONTEND_PID)"

echo ""
echo "All services started!"
echo ""
echo "Frontend: http://localhost:8000"
echo "Backend:  http://localhost:8001"
echo "API Docs: http://localhost:8001/docs"
echo ""
echo "Press Ctrl+C to stop all services"
echo ""

# Wait for both processes
wait $BACKEND_PID $FRONTEND_PID
