#!/bin/bash
# ==============================================================================
# Synthetic Digital Organism (SDO) - Primary Launch Script
# (c) 2026 DeliriousDreams Research. All Rights Reserved.
# ==============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "================================================================================"
echo "⚡ Starting Synthetic Digital Organism..."
echo "================================================================================"

# 1. Preflight Node.js check
if ! command -v node >/dev/null 2>&1; then
    echo "❌ ERROR: Node.js is not installed or not in PATH."
    echo "   Please install Node.js (v20.0 or higher) from https://nodejs.org"
    exit 1
fi

NODE_VER=$(node -v | sed 's/v//' | cut -d'.' -f1)
if [ "$NODE_VER" -lt 20 ]; then
    echo "⚠️ WARNING: Node.js version $(node -v) detected. v20.0+ is recommended."
fi

# 2. Preflight Python 3 & venv bootstrap
PYTHON_CMD=""
if command -v python3 >/dev/null 2>&1; then
    PYTHON_CMD="python3"
elif command -v python >/dev/null 2>&1; then
    PYTHON_CMD="python"
fi

if [ -n "$PYTHON_CMD" ]; then
    if [ ! -d "venv" ]; then
        echo "📦 Initializing isolated Python virtual environment (venv)..."
        $PYTHON_CMD -m venv venv 2>/dev/null || true
        if [ -f "venv/bin/pip" ]; then
            echo "📥 Installing required HAL sensory-motor packages..."
            venv/bin/pip install --quiet numpy sounddevice mss pynput evdev scipy opencv-python 2>/dev/null || true
        fi
    fi
else
    echo "⚠️ NOTE: Python 3 not found. Sensory hardware drivers may run in synthetic mode."
fi

# 3. License Notice
if [ ! -f "license.key" ]; then
    echo "ℹ️  NOTE: No 'license.key' detected in the root folder."
    echo "   Running in Community Evaluation Mode."
    echo "   To activate your Indie, Research, or Master license, place your 'license.key'"
    echo "   file into: $SCRIPT_DIR/license.key"
    echo ""
fi

# 4. Linux uinput permissions (if available)
if [ -e /dev/uinput ] && [ ! -w /dev/uinput ]; then
    if command -v sudo >/dev/null 2>&1; then
        sudo chmod 0666 /dev/uinput 2>/dev/null || true
    fi
fi

mkdir -p data/logs data/lancedb
rm -f .stop_sdo

echo "🌐 Opening Mission Control Dashboard at http://localhost:3001"
echo "Press Ctrl+C or run ./Stop-AGI.sh to stop the organism."
echo "================================================================================"

while true; do
    if [ -f .stop_sdo ]; then
        echo "🛑 [SDO Supervisor] Stop flag detected. Exiting supervisor."
        rm -f .stop_sdo
        break
    fi

    EXIT_CODE=0
    node --max-old-space-size=4096 dist/brain_server.bundle.js || EXIT_CODE=$?

    if [ "$EXIT_CODE" -eq 42 ]; then
        echo "🔄 [SDO Supervisor] Clean restart requested (Exit code 42). Rebooting in 1s..."
        sleep 1
        continue
    elif [ "$EXIT_CODE" -eq 0 ]; then
        echo "✅ [SDO Supervisor] SDO process stopped cleanly (Exit code 0)."
        break
    else
        echo "⚠️ [SDO Supervisor] Unexpected exit (Exit code $EXIT_CODE). Auto-recovering in 2s..."
        sleep 2
        continue
    fi
done
