#!/bin/bash
# Stop both backend and frontend services
# Enhanced to kill entire process trees and clean up orphans

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"

echo "🛑 Stopping SBA Gameplay Services..."
echo ""

# Function to kill process tree
kill_tree() {
    local pid=$1
    local sig=${2:-TERM}

    # Get all child PIDs
    local children=$(pgrep -P "$pid" 2>/dev/null || true)

    # Kill children first
    for child in $children; do
        kill_tree "$child" "$sig"
    done

    # Kill the parent
    if ps -p "$pid" > /dev/null 2>&1; then
        kill -"$sig" "$pid" 2>/dev/null || true
    fi
}

# Stop Backend
if [ -f "$LOG_DIR/backend.pid" ]; then
    BACKEND_PID=$(cat "$LOG_DIR/backend.pid")
    if ps -p "$BACKEND_PID" > /dev/null 2>&1; then
        echo "📡 Stopping Backend (PID: $BACKEND_PID)..."
        kill_tree "$BACKEND_PID" TERM
        sleep 1
        # Force kill if still running
        if ps -p "$BACKEND_PID" > /dev/null 2>&1; then
            kill_tree "$BACKEND_PID" KILL
        fi
        echo "   ✓ Backend stopped"
    else
        echo "   ⚠ Backend process not found"
    fi
    rm -f "$LOG_DIR/backend.pid"
else
    echo "   ⚠ No backend PID file found"
fi
echo ""

# Stop Frontend
if [ -f "$LOG_DIR/frontend.pid" ]; then
    FRONTEND_PID=$(cat "$LOG_DIR/frontend.pid")
    if ps -p "$FRONTEND_PID" > /dev/null 2>&1; then
        echo "🎨 Stopping Frontend (PID: $FRONTEND_PID)..."
        kill_tree "$FRONTEND_PID" TERM
        sleep 1
        # Force kill if still running
        if ps -p "$FRONTEND_PID" > /dev/null 2>&1; then
            kill_tree "$FRONTEND_PID" KILL
        fi
        echo "   ✓ Frontend stopped"
    else
        echo "   ⚠ Frontend process not found"
    fi
    rm -f "$LOG_DIR/frontend.pid"
else
    echo "   ⚠ No frontend PID file found"
fi
echo ""

# Aggressive cleanup: kill ALL related processes by pattern matching
echo "🔍 Checking for any remaining processes..."

# Kill all backend processes for this app (uvicorn OR python -m app.main)
BACKEND_PIDS=$(pgrep -f "python.*app\.main" 2>/dev/null || true)
UVICORN_PIDS=$(pgrep -f "uvicorn.*app\.main" 2>/dev/null || true)
ALL_BACKEND_PIDS="$BACKEND_PIDS $UVICORN_PIDS"
ALL_BACKEND_PIDS=$(echo "$ALL_BACKEND_PIDS" | tr ' ' '\n' | sort -u | tr '\n' ' ' | xargs)

if [ -n "$ALL_BACKEND_PIDS" ]; then
    echo "   Found orphaned backend processes: $ALL_BACKEND_PIDS"
    for pid in $ALL_BACKEND_PIDS; do
        kill_tree "$pid" KILL
    done
    echo "   ✓ Killed orphaned backend processes"
fi

# Also kill any processes on port 8000
PORT_8000_PIDS=$(lsof -ti :8000 2>/dev/null || true)
if [ -n "$PORT_8000_PIDS" ]; then
    echo "   Found processes on port 8000: $PORT_8000_PIDS"
    for pid in $PORT_8000_PIDS; do
        kill -9 "$pid" 2>/dev/null || true
    done
    echo "   ✓ Killed processes on port 8000"
fi

# Kill all nuxt dev processes in this directory
FRONTEND_PIDS=$(pgrep -f "nuxt.*dev" | while read pid; do
    if ps -p $pid -o args= | grep -q "$SCRIPT_DIR/frontend-sba"; then
        echo $pid
    fi
done)
if [ -n "$FRONTEND_PIDS" ]; then
    echo "   Found orphaned frontend processes: $FRONTEND_PIDS"
    for pid in $FRONTEND_PIDS; do
        kill_tree "$pid" KILL
    done
    echo "   ✓ Killed orphaned frontend processes"
fi

echo "✅ Services stopped successfully!"
