@echo off
setlocal EnableExtensions EnableDelayedExpansion
REM Keep this file ASCII-only (no Chinese). UTF-8 CJK in .bat breaks cmd.exe
REM on some Windows PCs: multi-byte chars can split "install" into "tall".
REM Script lives in scripts/; go to repo root before starting the service.
cd /d "%~dp0.."
title Proto Workbench + Version Service

echo.
echo   ========================================
echo    Proto Workbench + Version Service
echo   ========================================
echo   Opens the browser workbench automatically
echo   (default port 5502; picks another if busy).
echo   Real URL is printed in the log below.
echo.
echo   Keep this window open to preview pages
echo   and create version snapshots.
echo   Close this window = stop the service.
echo   ========================================
echo.

call :ensure_node_npm
if errorlevel 1 (
  echo.
  pause
  exit /b 1
)

echo   [OK] Node:
node -v
echo   [OK] npm:
call npm -v
echo.

call npm run version:serve
echo.
pause
exit /b 0

REM ============================================================
REM  Detect / setup Node.js + npm
REM ============================================================
:ensure_node_npm
call :refresh_path
call :has_node_npm
if not errorlevel 1 exit /b 0

echo   [Check] Node.js / npm not found. Trying auto setup...
echo.

set "SETUP_OK=0"

REM --- Prefer winget (common on Win10/11) ---
where winget >nul 2>nul
if not errorlevel 1 (
  echo   [Setup] Installing Node.js LTS via winget...
  winget install -e --id OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements
  if not errorlevel 1 set "SETUP_OK=1"
)

REM --- Fallback: Chocolatey ---
if "!SETUP_OK!"=="0" (
  where choco >nul 2>nul
  if not errorlevel 1 (
    echo   [Setup] Installing Node.js LTS via Chocolatey...
    choco install nodejs-lts -y
    if not errorlevel 1 set "SETUP_OK=1"
  )
)

REM --- Last resort: official LTS MSI silent install ---
if "!SETUP_OK!"=="0" (
  echo   [Setup] Downloading official Node.js LTS MSI...
  call :setup_node_msi
  if not errorlevel 1 set "SETUP_OK=1"
)

call :refresh_path
call :has_node_npm
if not errorlevel 1 (
  echo.
  echo   [OK] Node.js / npm is ready.
  exit /b 0
)

echo.
echo   [FAIL] Auto setup failed. Please install Node.js LTS manually:
echo          1. Open https://nodejs.org/ and download LTS
echo          2. Check "Add to PATH", then re-run this script
echo          3. Or in Cursor say: help me start the version service
echo.
start "" "https://nodejs.org/"
exit /b 1

:has_node_npm
where node >nul 2>nul
if errorlevel 1 exit /b 1
where npm >nul 2>nul
if errorlevel 1 exit /b 1
REM Verify they actually run (avoid empty PATH stubs)
node -v >nul 2>nul
if errorlevel 1 exit /b 1
call npm -v >nul 2>nul
if errorlevel 1 exit /b 1
exit /b 0

:refresh_path
REM Prepend common Node dirs and merge Machine/User PATH
if exist "%ProgramFiles%\nodejs\node.exe" set "PATH=%ProgramFiles%\nodejs;%PATH%"
if exist "%ProgramFiles(x86)%\nodejs\node.exe" set "PATH=%ProgramFiles(x86)%\nodejs;%PATH%"
if exist "%LOCALAPPDATA%\Programs\nodejs\node.exe" set "PATH=%LOCALAPPDATA%\Programs\nodejs;%PATH%"
for /f "usebackq delims=" %%i in (`powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User')"`) do set "PATH=%%i;%PATH%"
exit /b 0

:setup_node_msi
set "TMP_MSI=%TEMP%\node-lts-x64.msi"
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ProgressPreference='SilentlyContinue';" ^
  "$rel = Invoke-RestMethod -Uri 'https://nodejs.org/dist/index.json' -TimeoutSec 30;" ^
  "$lts = $rel | Where-Object { $_.lts } | Select-Object -First 1;" ^
  "if (-not $lts) { throw 'Unable to resolve Node LTS version' };" ^
  "$ver = $lts.version;" ^
  "$url = \"https://nodejs.org/dist/$ver/node-$ver-x64.msi\";" ^
  "Write-Host ('   Download: ' + $url);" ^
  "Invoke-WebRequest -Uri $url -OutFile '%TMP_MSI%' -UseBasicParsing;"
if errorlevel 1 (
  echo   [Error] Failed to download Node MSI (check network).
  exit /b 1
)
if not exist "%TMP_MSI%" (
  echo   [Error] Downloaded MSI not found.
  exit /b 1
)
echo   [Setup] Silent MSI install (UAC prompt may appear)...
msiexec /i "%TMP_MSI%" /qn ADDLOCAL=ALL
set "MSI_EC=!errorlevel!"
del /f /q "%TMP_MSI%" >nul 2>nul
if not "!MSI_EC!"=="0" (
  echo   [Error] MSI setup failed, exit code !MSI_EC!
  exit /b 1
)
exit /b 0
