@echo off
setlocal EnableExtensions
REM Apply staged LA StressLab update after the main process exits.
REM Prefer update_pending.json (UTF-8) so paths with accents work.
REM Fallback args: %1=APP_DIR  %2=STAGING  %3=PID  %4=EXE_NAME
REM Always write a breadcrumb to update_apply.log BEFORE PowerShell
REM (if PS 5.1 dies on parse, we still know the bat ran).

set "APP_DIR=%~1"
set "STAGING=%~2"
set "WAIT_PID=%~3"
set "EXE_NAME=%~4"
if "%EXE_NAME%"=="" set "EXE_NAME=LAStressLab.exe"
if "%APP_DIR%"=="" set "APP_DIR=%~dp0"
if "%APP_DIR:~-1%"=="\" set "APP_DIR=%APP_DIR:~0,-1%"

set "LOG=%APP_DIR%\update_apply.log"
echo [%DATE% %TIME%] BAT start AppDir=%APP_DIR% Staging=%STAGING% Pid=%WAIT_PID% Exe=%EXE_NAME%>> "%LOG%" 2>nul
echo [%DATE% %TIME%] BAT cwd=%CD% script=%~f0>> "%LOG%" 2>nul

REM Prefer update_apply.ps1 (Unicode-safe).
if not exist "%~dp0update_apply.ps1" (
  echo [%DATE% %TIME%] ERROR: update_apply.ps1 missing beside bat>> "%LOG%" 2>nul
  echo ERRO: update_apply.ps1 ausente
  set "RC=1"
  goto :fail
)

echo [%DATE% %TIME%] BAT launching powershell -File update_apply.ps1>> "%LOG%" 2>nul
if "%WAIT_PID%"=="" (
  powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0update_apply.ps1" -AppDir "%APP_DIR%" -Staging "%STAGING%" -ExeName "%EXE_NAME%"
) else (
  powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%~dp0update_apply.ps1" -AppDir "%APP_DIR%" -Staging "%STAGING%" -WaitPid "%WAIT_PID%" -ExeName "%EXE_NAME%"
)
set "RC=%ERRORLEVEL%"
echo [%DATE% %TIME%] BAT powershell exit=%RC%>> "%LOG%" 2>nul
if not "%RC%"=="0" goto :fail
exit /b 0

:fail
echo.
echo Falha ao aplicar update. Veja update_apply.log se existir.
echo O app anterior permanece.
echo Se existir %EXE_NAME%.bak, renomeie para %EXE_NAME% manualmente.
pause
exit /b %RC%
