#!/bin/bash
PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
PYTHON="$PROJECT_ROOT/Promethean/bin/python3"
FRONTEND_DIR="$PROJECT_ROOT/interface/web"
LOG_DIR="$PROJECT_ROOT/runtime"

mkdir -p "$LOG_DIR"

MEMORY_LOG="$LOG_DIR/memory.log"
BACKEND_LOG="$LOG_DIR/backend.log"
FRONTEND_LOG="$LOG_DIR/frontend.log"

_start() {
    # _start <label> <log_file> <work_dir> <cmd> [args...]
    local label="$1" log_file="$2" work_dir="$3"
    shift 3
    : > "$log_file"
    ( cd "$work_dir" && exec "$@" ) >> "$log_file" 2>&1 &
    echo $!
}

_check() {
    local label="$1" pid="$2" log_file="$3"
    if kill -0 "$pid" 2>/dev/null; then
        echo "$label STARTED"
    else
        echo "$label FAILED TO START"
        [ -s "$log_file" ] && tail -8 "$log_file" | sed 's/^/  /'
    fi
}

# Launch memory + backend together
MEMORY_PID=$(_start "NEXUS MEMORY SERVICE" "$MEMORY_LOG" "$PROJECT_ROOT" \
    "$PYTHON" -m uvicorn synapse.memory.service:app --host 0.0.0.0 --port 8001 --reload)

BACKEND_PID=$(_start "NEXUS BACKEND SERVICE" "$BACKEND_LOG" "$PROJECT_ROOT" \
    "$PYTHON" -m uvicorn synapse.main:sio_app --host 0.0.0.0 --port 8000 --reload)

sleep 3
_check "NEXUS MEMORY SERVICE" "$MEMORY_PID" "$MEMORY_LOG"
_check "NEXUS BACKEND SERVICE" "$BACKEND_PID" "$BACKEND_LOG"

# Frontend last
FRONTEND_PID=$(_start "NEXUS FRONTEND SERVICE" "$FRONTEND_LOG" "$FRONTEND_DIR" \
    npm run dev)

sleep 5
_check "NEXUS FRONTEND SERVICE" "$FRONTEND_PID" "$FRONTEND_LOG"

_shutdown() {
    echo ''
    echo 'Stopping NexusOS...'
    # First TERM the processes we directly spawned.
    kill "$MEMORY_PID" "$BACKEND_PID" "$FRONTEND_PID" 2>/dev/null
    # uvicorn --reload leaves a worker child holding the port and `npm run dev`
    # reparents vite, so the direct kills above orphan survivors. Delegate to the
    # management CLI's port-based teardown, which reliably clears all three ports.
    "$PROJECT_ROOT/management/nexus-cli.sh" stop >/dev/null 2>&1
    echo 'NEXUS STOPPED'
    exit
}
trap _shutdown SIGINT SIGTERM SIGHUP
wait
