@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 running.
cd /d "%~dp0.."
title Update PM Toolkit

echo.
echo   ========================================
echo    Update PM Toolkit
echo   ========================================
echo   1^) npm update @deppon/pm-toolkit
echo   2^) npm run pm:update  (sync skills / agents)
echo.
echo   Note: overwrites toolkit files in this repo;
echo         does NOT overwrite business prototype pages.
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.

echo   ---- Step 1/2: upgrade @deppon/pm-toolkit ----
call npm update @deppon/pm-toolkit
if errorlevel 1 (
  echo.
  echo   [FAIL] npm update failed. Check network / registry access.
  echo.
  pause
  exit /b 1
)
echo.

echo   ---- Step 2/2: sync toolkit assets (pm:update) ----
call npm run pm:update
if errorlevel 1 (
  echo.
  echo   [FAIL] pm:update failed.
  echo.
  pause
  exit /b 1
)

echo.
echo   ========================================
echo    Done: toolkit upgraded and synced.
echo   ========================================
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.
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
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
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
