@echo off
title NomadArch Installer
color 0A
setlocal enabledelayedexpansion

echo.
echo  ███╗   ██╗ ██████╗ ███╗   ███╗ █████╗ ██████╗  █████╗ ██████╗  ██████╗██╗  ██╗
echo  ████╗  ██║██╔═══██╗████╗ ████║██╔══██╗██╔══██╗██╔══██╗██╔════╝██║  ██║
echo  ██╔██╗ ██║██║   ██║██╔████╔██║███████║██║  ██║███████║██████╔╝██║     ███████║
echo  ██║╚██╗██║██║   ██║██║╚██╔╝██║██╔══██║██║  ██║██╔══██║██╔══██╗██║     ██╔══██║
echo  ██║ ╚████║╚██████╔╝██║ ╚═╝ ██║██║  ██║██████╔╝██║  ██║██║  ██║╚██████╗██║  ██║
echo  ╚═╝  ╚═══╝ ╚═════╝ ╚═╝     ╚═╝╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝
echo.
echo  INSTALLER - Enhanced with Auto-Dependency Resolution
echo  ═══════════════════════════════════════════════════════════════════════════════
echo.

set ERRORS=0
set WARNINGS=0

cd /d "%~dp0"

echo [STEP 1/6] Checking System Requirements...
echo.

:: Check for Administrator privileges
net session >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [WARN] Not running as Administrator. Some operations may fail.
    set /a WARNINGS+=1
    echo.
)

:: Check for Node.js
echo [INFO] Checking Node.js...
where node >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [ERROR] Node.js not found!
    echo.
    echo NomadArch requires Node.js to run.
    echo.
    echo Download from: https://nodejs.org/
    echo Recommended: Node.js 18.x LTS or 20.x LTS
    echo.
    echo Opening download page...
    start "" "https://nodejs.org/"
    echo.
    echo Please install Node.js and run this installer again.
    echo.
    pause
    exit /b 1
)
for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
echo [OK] Node.js detected: %NODE_VERSION%

:: Check Node.js version (require 18+)
for /f "tokens=1,2 delims=." %%a in ("%NODE_VERSION:v=%") do (
    set MAJOR=%%a
    set MINOR=%%b
)
if %MAJOR% lss 18 (
    echo [WARN] Node.js version is too old (found v%MAJOR%.%MINOR%, required 18+)
    echo [INFO] Please update Node.js from: https://nodejs.org/
    set /a WARNINGS+=1
)

:: Check for npm
echo [INFO] Checking npm...
where npm >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [ERROR] npm not found! This should come with Node.js.
    echo Please reinstall Node.js from: https://nodejs.org/
    set /a ERRORS+=1
)
for /f "tokens=*" %%i in ('npm --version') do set NPM_VERSION=%%i
echo [OK] npm detected: %NPM_VERSION%

:: Check for Git (optional but recommended)
echo [INFO] Checking Git...
where git >nul 2>&1
if %ERRORLEVEL% neq 0 (
    echo [WARN] Git not found (optional but recommended)
    echo [INFO] Install from: https://git-scm.com/
    set /a WARNINGS+=1
) else (
    for /f "tokens=*" %%i in ('git --version') do set GIT_VERSION=%%i
    echo [OK] Git detected: %GIT_VERSION%
)

:: Check for Python (optional, for some tools)
echo [INFO] Checking Python...
where python >nul 2>&1
if %ERRORLEVEL% neq 0 (
    where python3 >nul 2>&1
    if %ERRORLEVEL% neq 0 (
        echo [WARN] Python not found (optional, required for some build tools)
        echo [INFO] Install from: https://www.python.org/downloads/
        set /a WARNINGS+=1
    ) else (
        echo [OK] Python3 detected
    )
) else (
    for /f "tokens=2" %%i in ('python --version') do set PY_VERSION=%%i
    echo [OK] Python detected: %PY_VERSION%
)

:: Check disk space (at least 2GB free)
for /f "tokens=3" %%a in ('dir /-c "%~dp0" ^| find "bytes free"') do set FREE_SPACE=%%a
set /a FREE_SPACE_GB=!FREE_SPACE!/1024/1024/1024
if !FREE_SPACE_GB! lss 2 (
    echo [WARN] Low disk space (!FREE_SPACE_GB! GB free, recommended 2GB+)
    set /a WARNINGS+=1
) else (
    echo [OK] Disk space: !FREE_SPACE_GB! GB free
)

echo.
echo [STEP 2/6] Cleaning Previous Installation...
echo.

if exist "node_modules" (
    echo [INFO] Found existing node_modules, cleaning...
    if exist "node_modules\.package-lock.json" (
        del /f /q "node_modules\.package-lock.json" 2>nul
    )
    echo [OK] Cleaned previous installation artifacts
) else (
    echo [OK] No previous installation found
)

echo.
echo [STEP 3/6] Downloading OpenCode Binary...
echo.

if not exist "bin" mkdir bin
if not exist "bin\opencode.exe" (
    echo [SETUP] Downloading opencode.exe from GitHub releases...
    echo [INFO] This is required for workspace functionality.
    curl -L -o "bin\opencode.exe" "https://github.com/NeuralNomadsAI/NomadArch/releases/latest/download/opencode.exe"
    if %ERRORLEVEL% neq 0 (
        echo [WARN] Failed to download opencode.exe automatically.
        echo [INFO] You can install OpenCode CLI manually from: https://opencode.ai/
        echo [INFO] Or download opencode.exe and place it in bin/ folder
        echo [INFO] Without opencode.exe, workspace creation will fail.
        set /a WARNINGS+=1
    ) else (
        echo [OK] opencode.exe downloaded successfully
    )
) else (
    echo [OK] opencode.exe already exists
)

echo.
echo [STEP 4/6] Installing Dependencies...
echo.
echo This may take 3-10 minutes depending on your internet speed.
echo Please be patient and do not close this window.
echo.

call npm install
if %ERRORLEVEL% neq 0 (
    echo.
    echo [ERROR] npm install failed!
    echo.
    echo Common solutions:
    echo  1. Check your internet connection
    echo  2. Try running as Administrator
    echo 3. Clear npm cache: npm cache clean --force
    echo 4. Delete node_modules and try again
    echo.
    echo Attempting to clear npm cache and retry...
    call npm cache clean --force
    echo Retrying installation...
    call npm install
    if %ERRORLEVEL% neq 0 (
        echo [ERROR] Installation failed after retry.
        set /a ERRORS+=1
    )
) else (
    echo [OK] Dependencies installed successfully
)

echo.
echo [STEP 5/6] Building NomadArch...
echo.
echo This may take 2-5 minutes depending on your system.
echo.

call npm run build
if %ERRORLEVEL% neq 0 (
    echo.
    echo [ERROR] Build failed!
    echo.
    echo Common solutions:
    echo  1. Check that Node.js version is 18+ (node --version)
    echo 2. Clear npm cache: npm cache clean --force
    echo 3. Delete node_modules and reinstall: rm -rf node_modules ^&^& npm install
    echo 4. Check the error messages above for specific issues
    echo.
    set /a ERRORS+=1
) else (
    echo [OK] Build completed successfully
)

echo.
echo [STEP 6/6] Verifying Installation...
echo.

:: Check UI build
if not exist "packages\ui\dist" (
    echo [WARN] UI build not found
    set /a WARNINGS+=1
) else (
    echo [OK] UI build verified
)

:: Check Server build
if not exist "packages\server\dist\bin.js" (
    echo [WARN] Server build not found
    set /a WARNINGS+=1
) else (
    echo [OK] Server build verified
)

:: Check Electron build
if not exist "packages\electron-app\dist\main\main.js" (
    echo [WARN] Electron build not found
    set /a WARNINGS+=1
) else (
    echo [OK] Electron build verified
)

:: Check opencode.exe
if not exist "bin\opencode.exe" (
    echo [WARN] opencode.exe not found. Workspace creation will fail.
    echo [INFO] Download from: https://github.com/NeuralNomadsAI/NomadArch/releases/latest/download/opencode.exe
    echo [INFO] Or install OpenCode CLI from: https://opencode.ai/
    set /a WARNINGS+=1
) else (
    echo [OK] opencode.exe verified
)

echo.
echo [STEP 7/7] Installation Summary
echo.

if %ERRORS% gtr 0 (
    echo.
    echo  ═══════════════════════════════════════════════════════════════════════════════
    echo  [FAILED] Installation encountered %ERRORS% error^(s^)!
    echo.
    echo Please review the error messages above and try again.
    echo For help, see: https://github.com/NeuralNomadsAI/NomadArch/issues
    echo  ═══════════════════════════════════════════════════════════════════════════════
    echo.
    pause
    exit /b 1
)

echo.
echo  ═══════════════════════════════════════════════════════════════════════════════
echo  [SUCCESS] Installation Complete!
echo.
if %WARNINGS% gtr 0 (
    echo  [WARN] There were %WARNINGS% warning^(s^) during installation.
    echo  Review the warnings above. Most warnings are non-critical.
    echo.
)
echo  You can now run NomadArch using:
echo    - Launch-Windows.bat        ^(Production mode^)
echo    - Launch-Dev-Windows.bat   ^(Developer mode with hot reload^)
echo    - NomadArch.vbs            ^(Silent mode, no console window^)
echo.
echo  For help and documentation, see: README.md
echo  For troubleshooting, see: TROUBLESHOOTING.md
echo  ═══════════════════════════════════════════════════════════════════════════════
echo.
echo  Press any key to start NomadArch now, or close this window to start later...
pause >nul

:: Offer to start the app
echo.
echo [OPTION] Would you like to start NomadArch now? ^(Y/N^)
set /p START_APP="> "
if /i "%START_APP%"=="Y" (
    echo.
    echo [INFO] Starting NomadArch...
    call Launch-Windows.bat
) else (
    echo.
    echo [INFO] You can start NomadArch later by running Launch-Windows.bat
    echo.
)

exit /b 0
