@echo off
chcp 65001 >nul
setlocal
set "SCRIPT_DIR=%~dp0"
set "DEFAULT_START=0"
if "%~1"=="" set "DEFAULT_START=1"
if "%PROVIDER_AGENT_ENV_FILE%"=="" (set "ENV_FILE=%SCRIPT_DIR%config.txt") else (set "ENV_FILE=%PROVIDER_AGENT_ENV_FILE%")
set "BINARY=%SCRIPT_DIR%token-provider-agent.exe"

if not exist "%ENV_FILE%" (
  echo missing env file: %ENV_FILE% 1>&2
  echo edit config.txt next to this script, or set PROVIDER_AGENT_ENV_FILE 1>&2
  call :pause_if_default 1
  exit /b 1
)

if not exist "%BINARY%" (
  echo missing executable binary: %BINARY% 1>&2
  call :pause_if_default 1
  exit /b 1
)

cd /d "%SCRIPT_DIR%"
for /f "usebackq eol=# tokens=1,* delims==" %%A in ("%ENV_FILE%") do (
  if not "%%A"=="" set "%%A=%%B"
)

if "%~1"=="" (
  "%BINARY%" start
) else (
  "%BINARY%" %*
)
set "EXIT_CODE=%ERRORLEVEL%"
call :pause_if_default %EXIT_CODE%
exit /b %EXIT_CODE%

:pause_if_default
if not "%DEFAULT_START%"=="1" exit /b %~1
echo.
if "%~1"=="0" (
  echo Provider Agent 已退出。
) else (
  echo Provider Agent 启动失败，退出码 %~1。
)
echo 按任意键关闭窗口...
pause >nul
exit /b %~1
