#!/bin/bash

# Safe AI Debug Process Management
# Only manages processes running from ai-debug-local-mcp/core directory

PROJECT_DIR="/Users/og/src/ai-debug-local-mcp/core"

get_ai_debug_processes() {
    # Find all mix phx.server processes
    for pid in $(ps aux | grep "mix phx.server" | grep -v grep | awk '{print $2}'); do
        # Check if working directory matches our project
        if lsof -p $pid 2>/dev/null | grep -q "$PROJECT_DIR"; then
            echo $pid
        fi
    done
}

stop_ai_debug() {
    echo "🔍 Looking for AI Debug processes..."
    pids=$(get_ai_debug_processes)
    
    if [ -z "$pids" ]; then
        echo "✅ No AI Debug processes found"
        return 0
    fi
    
    echo "🛑 Found AI Debug processes: $pids"
    for pid in $pids; do
        echo "   Stopping process $pid..."
        kill $pid
        sleep 1
        if ! kill -0 $pid 2>/dev/null; then
            echo "   ✅ Process $pid stopped"
        else
            echo "   🔄 Force killing process $pid..."
            kill -9 $pid
        fi
    done
}

status_ai_debug() {
    echo "🔍 AI Debug Process Status:"
    pids=$(get_ai_debug_processes)
    
    if [ -z "$pids" ]; then
        echo "   ❌ No AI Debug processes running"
        return 1
    fi
    
    for pid in $pids; do
        port=$(lsof -i -p $pid 2>/dev/null | grep LISTEN | awk '{print $9}' | cut -d: -f2)
        echo "   ✅ Process $pid running on port $port"
        echo "      Working directory: $(lsof -p $pid | grep cwd | awk '{print $9}')"
    done
}

restart_ai_debug() {
    echo "🔄 Restarting AI Debug..."
    stop_ai_debug
    sleep 2
    echo "🚀 Starting AI Debug on port 9090..."
    cd "$PROJECT_DIR"
    AI_DEBUG_PORT=9090 nohup mix phx.server > phoenix.log 2>&1 &
    sleep 3
    status_ai_debug
}

case "$1" in
    "stop")
        stop_ai_debug
        ;;
    "status")
        status_ai_debug
        ;;
    "restart")
        restart_ai_debug
        ;;
    *)
        echo "Usage: $0 {stop|status|restart}"
        echo ""
        echo "Commands:"
        echo "  stop    - Safely stop AI Debug processes (only from $PROJECT_DIR)"
        echo "  status  - Show AI Debug process status and ports"
        echo "  restart - Stop and restart AI Debug on port 9090"
        exit 1
        ;;
esac