@echo off
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion

title NomadArch Installer - Windows

echo.
echo ╔═══════════════════════════════════════════════════════════════╗
echo ║           NomadArch Installer for Windows                     ║
echo ║           Version: 0.6.0 - Robust Edition                     ║
echo ╚═══════════════════════════════════════════════════════════════╝
echo.

set SCRIPT_DIR=%~dp0
set SCRIPT_DIR=%SCRIPT_DIR:~0,-1%
set TARGET_DIR=%SCRIPT_DIR%
set BIN_DIR=%TARGET_DIR%\bin
set LOG_FILE=%TARGET_DIR%\install.log
set TEMP_DIR=%TARGET_DIR%\.install-temp

set ERRORS=0
set WARNINGS=0
set SKIP_OPENCODE=1
set NODE_INSTALLED_NOW=0

echo [%date% %time%] ========== Installer started ========== >> "%LOG_FILE%"

REM ═══════════════════════════════════════════════════════════════
REM STEP 1: OS and Architecture Detection
REM ═══════════════════════════════════════════════════════════════
echo [STEP 1/8] Detecting System...

for /f "tokens=2 delims==" %%a in ('wmic os get osarchitecture /value 2^>nul ^| find "="') do set ARCH_RAW=%%a
if "!ARCH_RAW!"=="" set ARCH_RAW=64-bit

echo !ARCH_RAW! | findstr /i "64" >nul
if !ERRORLEVEL! equ 0 (
    set ARCH=x64
) else (
    set ARCH=x86
)

for /f "tokens=4-5 delims=. " %%i in ('ver') do set WIN_VER=%%i.%%j
echo [OK] Windows Version: !WIN_VER!
echo [OK] Architecture: !ARCH!
echo [%date% %time%] OS: Windows !WIN_VER!, Arch: !ARCH! >> "%LOG_FILE%"

REM ═══════════════════════════════════════════════════════════════
REM STEP 2: Check Write Permissions
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 2/8] Checking Write Permissions...

if not exist "%BIN_DIR%" mkdir "%BIN_DIR%" 2>nul
if not exist "%TEMP_DIR%" mkdir "%TEMP_DIR%" 2>nul

echo. > "%SCRIPT_DIR%\.write-test.tmp" 2>nul
if !ERRORLEVEL! neq 0 (
    echo [WARN] Cannot write to: %SCRIPT_DIR%
    echo [INFO] Using fallback location in user profile...
    set TARGET_DIR=%USERPROFILE%\NomadArch
    set BIN_DIR=!TARGET_DIR!\bin
    set LOG_FILE=!TARGET_DIR!\install.log
    set TEMP_DIR=!TARGET_DIR!\.install-temp
    if not exist "!TARGET_DIR!" mkdir "!TARGET_DIR!"
    if not exist "!BIN_DIR!" mkdir "!BIN_DIR!"
    if not exist "!TEMP_DIR!" mkdir "!TEMP_DIR!"
    echo [OK] Using fallback: !TARGET_DIR!
) else (
    del "%SCRIPT_DIR%\.write-test.tmp" 2>nul
    echo [OK] Write permissions verified
)
echo [%date% %time%] Install target: %TARGET_DIR% >> "%LOG_FILE%"

REM ═══════════════════════════════════════════════════════════════
REM STEP 3: Check and Install Node.js
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 3/8] Checking Node.js...

set NODE_OK=0
set NPM_OK=0

where node >nul 2>&1
if !ERRORLEVEL! equ 0 (
    for /f "tokens=*" %%v in ('node --version 2^>nul') do set NODE_VERSION=%%v
    if defined NODE_VERSION (
        echo [OK] Node.js found: !NODE_VERSION!
        set NODE_OK=1
    )
)

if !NODE_OK! equ 0 (
    echo [INFO] Node.js not found. Attempting automatic installation...
    echo [%date% %time%] Node.js not found, attempting install >> "%LOG_FILE%"
    
    REM Try winget first (Windows 10 1709+)
    where winget >nul 2>&1
    if !ERRORLEVEL! equ 0 (
        echo [INFO] Installing Node.js via winget...
        winget install -e --id OpenJS.NodeJS.LTS --accept-source-agreements --accept-package-agreements --silent
        if !ERRORLEVEL! equ 0 (
            set NODE_INSTALLED_NOW=1
            echo [OK] Node.js installed via winget
        ) else (
            echo [WARN] Winget install failed, trying alternative...
        )
    )
    
    REM Try chocolatey if winget failed
    if !NODE_INSTALLED_NOW! equ 0 (
        where choco >nul 2>&1
        if !ERRORLEVEL! equ 0 (
            echo [INFO] Installing Node.js via Chocolatey...
            choco install nodejs-lts -y
            if !ERRORLEVEL! equ 0 (
                set NODE_INSTALLED_NOW=1
                echo [OK] Node.js installed via Chocolatey
            )
        )
    )
    
    REM Direct download as last resort
    if !NODE_INSTALLED_NOW! equ 0 (
        echo [INFO] Downloading Node.js installer directly...
        set NODE_INSTALLER=%TEMP_DIR%\node-installer.msi
        
        REM Download using PowerShell
        powershell -NoProfile -ExecutionPolicy Bypass -Command ^
            "$ProgressPreference = 'SilentlyContinue'; " ^
            "try { " ^
            "  Invoke-WebRequest -Uri 'https://nodejs.org/dist/v20.10.0/node-v20.10.0-x64.msi' -OutFile '%TEMP_DIR%\node-installer.msi' -UseBasicParsing; " ^
            "  exit 0 " ^
            "} catch { exit 1 }"
        
        if exist "%TEMP_DIR%\node-installer.msi" (
            echo [INFO] Running Node.js installer...
            msiexec /i "%TEMP_DIR%\node-installer.msi" /qn /norestart
            if !ERRORLEVEL! equ 0 (
                set NODE_INSTALLED_NOW=1
                echo [OK] Node.js installed successfully
            ) else (
                echo [ERROR] Node.js MSI installation failed
            )
            del "%TEMP_DIR%\node-installer.msi" 2>nul
        ) else (
            echo [ERROR] Failed to download Node.js installer
        )
    )
    
    if !NODE_INSTALLED_NOW! equ 1 (
        echo.
        echo ╔═══════════════════════════════════════════════════════════════╗
        echo ║  IMPORTANT: Node.js was just installed!                       ║
        echo ║  Please CLOSE this window and run Install-Windows.bat again.  ║
        echo ║  This is required for the PATH to update.                     ║
        echo ╚═══════════════════════════════════════════════════════════════╝
        echo.
        echo [%date% %time%] Node.js installed, restart required >> "%LOG_FILE%"
        pause
        exit /b 0
    ) else (
        echo.
        echo [ERROR] Could not install Node.js automatically.
        echo.
        echo Please install Node.js manually:
        echo   1. Go to https://nodejs.org/
        echo   2. Download and install the LTS version
        echo   3. Restart this installer
        echo.
        echo [%date% %time%] ERROR: Node.js installation failed >> "%LOG_FILE%"
        set /a ERRORS+=1
        goto :SUMMARY
    )
)

REM Verify npm
where npm >nul 2>&1
if !ERRORLEVEL! equ 0 (
    for /f "tokens=*" %%v in ('npm --version 2^>nul') do set NPM_VERSION=%%v
    if defined NPM_VERSION (
        echo [OK] npm found: !NPM_VERSION!
        set NPM_OK=1
    )
)

if !NPM_OK! equ 0 (
    echo [ERROR] npm not found. This usually comes with Node.js.
    echo [%date% %time%] ERROR: npm not found >> "%LOG_FILE%"
    set /a ERRORS+=1
    goto :SUMMARY
)

REM ═══════════════════════════════════════════════════════════════
REM STEP 4: Check Git (optional)
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 4/8] Checking Git (optional)...

where git >nul 2>&1
if !ERRORLEVEL! equ 0 (
    for /f "tokens=*" %%v in ('git --version 2^>nul') do set GIT_VERSION=%%v
    echo [OK] !GIT_VERSION!
) else (
    echo [INFO] Git not found (optional - not required for basic usage)
    set /a WARNINGS+=1
)

REM ═══════════════════════════════════════════════════════════════
REM STEP 5: Install npm Dependencies
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 5/8] Installing Dependencies...

cd /d "%SCRIPT_DIR%"

if not exist "package.json" (
    echo [ERROR] package.json not found in %SCRIPT_DIR%
    echo [ERROR] Make sure you extracted the full NomadArch package.
    echo [%date% %time%] ERROR: package.json missing >> "%LOG_FILE%"
    set /a ERRORS+=1
    goto :SUMMARY
)

echo [INFO] Running npm install (this may take a few minutes)...
echo [%date% %time%] Running npm install >> "%LOG_FILE%"

call npm install --no-audit --no-fund 2>&1
if !ERRORLEVEL! neq 0 (
    echo [WARN] npm install had issues, trying with legacy peer deps...
    call npm install --legacy-peer-deps --no-audit --no-fund 2>&1
    if !ERRORLEVEL! neq 0 (
        echo [ERROR] npm install failed!
        echo [%date% %time%] ERROR: npm install failed >> "%LOG_FILE%"
        set /a ERRORS+=1
        goto :SUMMARY
    )
)
echo [OK] Dependencies installed

REM ═══════════════════════════════════════════════════════════════
REM STEP 6: OpenCode Binary (OPTIONAL)
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 6/8] OpenCode Binary Setup...
echo.
echo ╔═══════════════════════════════════════════════════════════════╗
echo ║  NomadArch supports Binary-Free Mode!                         ║
echo ║  You can skip the OpenCode binary and use free cloud models:  ║
echo ║  - GPT-5 Nano, Grok Code, GLM-4.7, Doubao, and more          ║
echo ╚═══════════════════════════════════════════════════════════════╝
echo.

set SKIP_OPENCODE=1
echo [OK] Using Binary-Free Mode (default)
echo [%date% %time%] Using Binary-Free Mode >> "%LOG_FILE%"

REM ═══════════════════════════════════════════════════════════════
REM STEP 7: Build UI Assets
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 7/8] Building UI Assets...

if exist "%SCRIPT_DIR%\packages\ui\dist\index.html" (
    echo [OK] UI build already exists
) else (
    echo [INFO] Building UI (this may take 1-2 minutes)...
    pushd "%SCRIPT_DIR%\packages\ui"
    call npm run build 2>&1
    if !ERRORLEVEL! neq 0 (
        echo [ERROR] UI build failed!
        echo [%date% %time%] ERROR: UI build failed >> "%LOG_FILE%"
        popd
        set /a ERRORS+=1
        goto :SUMMARY
    )
    popd
    echo [OK] UI assets built successfully
)

REM ═══════════════════════════════════════════════════════════════
REM STEP 8: Health Check and Summary
REM ═══════════════════════════════════════════════════════════════
echo.
echo [STEP 8/8] Running Health Check...

set HEALTH_OK=1

if not exist "%SCRIPT_DIR%\package.json" (
    echo [FAIL] package.json missing
    set HEALTH_OK=0
)

if not exist "%SCRIPT_DIR%\packages\ui" (
    echo [FAIL] packages\ui directory missing
    set HEALTH_OK=0
)

if not exist "%SCRIPT_DIR%\packages\server" (
    echo [FAIL] packages\server directory missing
    set HEALTH_OK=0
)

if not exist "%SCRIPT_DIR%\packages\ui\dist\index.html" (
    echo [FAIL] UI build missing (packages\ui\dist\index.html)
    set HEALTH_OK=0
)

if not exist "%SCRIPT_DIR%\node_modules" (
    echo [FAIL] node_modules directory missing
    set HEALTH_OK=0
)

if !HEALTH_OK! equ 1 (
    echo [OK] All health checks passed
) else (
    echo [ERROR] Health checks failed
    set /a ERRORS+=1
)

:SUMMARY
echo.
echo ╔═══════════════════════════════════════════════════════════════╗
echo ║                    INSTALLATION SUMMARY                       ║
echo ╚═══════════════════════════════════════════════════════════════╝
echo.
echo   Install Directory: %TARGET_DIR%
echo   Architecture:      !ARCH!
if defined NODE_VERSION echo   Node.js:           !NODE_VERSION!
if defined NPM_VERSION echo   npm:               !NPM_VERSION!
echo   Mode:              Binary-Free Mode
echo   Errors:            !ERRORS!
echo   Warnings:          !WARNINGS!
echo   Log File:          %LOG_FILE%
echo.

if !ERRORS! gtr 0 (
    echo ╔═══════════════════════════════════════════════════════════════╗
    echo ║  INSTALLATION FAILED                                          ║
    echo ╚═══════════════════════════════════════════════════════════════╝
    echo.
    echo Review the errors above and check the log file: %LOG_FILE%
    echo.
    echo Common fixes:
    echo   1. Run as Administrator (right-click, Run as administrator)
    echo   2. Ensure internet connection is stable
    echo   3. Disable antivirus temporarily
    echo   4. Install Node.js manually from https://nodejs.org/
    echo.
    echo [%date% %time%] Installation FAILED with !ERRORS! errors >> "%LOG_FILE%"
) else (
    echo ╔═══════════════════════════════════════════════════════════════╗
    echo ║  INSTALLATION SUCCESSFUL!                                     ║
    echo ╚═══════════════════════════════════════════════════════════════╝
    echo.
    echo To start NomadArch, run:
    echo   Launch-Windows.bat
    echo.
    echo Available Free Models:
    echo   - GPT-5 Nano (fast)
    echo   - Grok Code (coding)
    echo   - GLM-4.7 (general)
    echo   - Doubao (creative)
    echo   - Big Pickle (experimental)
    echo.
    echo [%date% %time%] Installation SUCCESSFUL >> "%LOG_FILE%"
)

echo.
echo Press any key to exit...
pause >nul
exit /b !ERRORS!
