#!/bin/bash
# Auto-start script for Church Music System Development Mode
# Ensures all features work with hot-reload

set -e

PROJECT_DIR="/media/pts/Website/Church_HOP_MusicData"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# WARNING: Check if production services are running
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║           Church Music System - Development Mode               ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Check if systemd services are running
if systemctl is-active --quiet church-music-backend.service; then
    echo "⚠️  WARNING: Production backend service is running!"
    echo "   This will cause port conflicts (port 8080)"
    echo ""
    read -p "   Stop production services and continue? [y/N] " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        sudo systemctl stop church-music-backend.service
        sudo systemctl stop church-music-frontend.service
        echo "✓ Production services stopped"
    else
        echo "❌ Cancelled. Stop services manually or use production mode."
        exit 1
    fi
fi

# Check for existing dev processes
if [ -f /tmp/church-backend.pid ]; then
    OLD_PID=$(cat /tmp/church-backend.pid)
    if ps -p $OLD_PID > /dev/null 2>&1; then
        echo "⚠️  Killing old backend process (PID: $OLD_PID)"
        kill -9 $OLD_PID 2>/dev/null || true
    fi
    rm /tmp/church-backend.pid
fi

if [ -f /tmp/church-frontend.pid ]; then
    OLD_PID=$(cat /tmp/church-frontend.pid)
    if ps -p $OLD_PID > /dev/null 2>&1; then
        echo "⚠️  Killing old frontend process (PID: $OLD_PID)"
        kill -9 $OLD_PID 2>/dev/null || true
    fi
    rm /tmp/church-frontend.pid
fi

# Start backend
echo ""
echo "Starting backend in development mode..."
cd $BACKEND_DIR
source venv/bin/activate
python app.py > /tmp/church-backend.log 2>&1 &
echo $! > /tmp/church-backend.pid
echo "✓ Backend started (PID: $(cat /tmp/church-backend.pid))"

# Wait for backend
sleep 3

# Start frontend on port 5100
echo "Starting frontend in development mode..."
cd $FRONTEND_DIR
PORT=5100 npm start > /tmp/church-frontend.log 2>&1 &
echo $! > /tmp/church-frontend.pid
echo "✓ Frontend started (PID: $(cat /tmp/church-frontend.pid))"

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  ✅ Church Music System running in DEVELOPMENT mode            ║"
echo "║                                                                ║"
echo "║  Frontend: http://localhost:5100                               ║"
echo "║  Backend:  http://localhost:8080                               ║"
echo "║                                                                ║"
echo "║  To stop: ./stop-dev-mode.sh                                   ║"
echo "║  View logs: tail -f /tmp/church-*.log                          ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
