@echo off
title Synthetic Digital Organism
cd /d "%~dp0"

echo ================================================================================
echo Starting Synthetic Digital Organism (%PROCESSOR_ARCHITECTURE%)...
if /i "%PROCESSOR_ARCHITECTURE%"=="ARM64" (
    echo [Platform] Windows on ARM64 detected: Snapdragon / WoA.
) else (
    echo [Platform] Windows x64 detected.
)
echo ================================================================================

where node >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    echo [ERROR] Node.js is not installed or not found in PATH.
    echo Please install Node.js v20.0+ for Windows from https://nodejs.org
    pause
    exit /b 1
)

where python >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    if not exist "venv" (
        echo Initializing isolated Python virtual environment...
        python -m venv venv >nul 2>&1
        if exist "venv\Scripts\pip.exe" (
            echo Installing required sensory-motor packages...
            venv\Scripts\pip install --quiet numpy sounddevice mss pynput scipy opencv-python >nul 2>&1
        )
    )
)

where cargo >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    if exist "core\Cargo.toml" (
        if not exist "core\index.win32.node" (
            echo [SDO Preflight] Rust toolchain detected. Checking native Windows accelerator...
            cargo build --manifest-path core\Cargo.toml --release >nul 2>&1
            if exist "core\target\release\sdo_core.dll" (
                copy /y "core\target\release\sdo_core.dll" "core\index.node" >nul 2>&1
                copy /y "core\target\release\sdo_core.dll" "core\index.win32.node" >nul 2>&1
                echo [SDO Preflight] Native Windows accelerator successfully compiled.
            )
        )
    )
)

if not exist "license.key" (
    echo Note: No license.key detected in this directory.
    echo Running in Community Evaluation Mode.
    echo To activate, place your license.key in this folder.
    echo.
)

if not exist "data\logs" mkdir "data\logs"
if not exist "data\lancedb" mkdir "data\lancedb"

echo Opening Mission Control Dashboard at http://localhost:3001
echo Press Ctrl+C or run Stop-AGI.bat to terminate.
echo ================================================================================

:RUN_LOOP
node dist\brain_server.bundle.js
if %ERRORLEVEL% EQU 42 (
    echo [SDO Supervisor] Clean restart requested. Rebooting in 1s...
    timeout /t 1 /nobreak >nul
    goto RUN_LOOP
)
if %ERRORLEVEL% NEQ 0 (
    echo [SDO Supervisor] Process exited with error code %ERRORLEVEL%.
    pause
)
