@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "NO_PAUSE=%~1"
set "APP_DIR=%~dp0app"
set "DATA_DIR=%LOCALAPPDATA%\Pinterest AI Operator"
set "LOG_DIR=%DATA_DIR%\Logs"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

set "NODE_EXE=%~dp0runtime\node\node.exe"
if exist "%NODE_EXE%" goto node_ready
where node >nul 2>nul
if errorlevel 1 (
  echo.
  echo 未找到 Node.js。请确认安装包完整，或先安装 Node.js 20+：
  echo https://nodejs.org/
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)
set "NODE_EXE=node"
:node_ready

if not exist "%APP_DIR%\node_modules\next\dist\bin\next" (
  echo.
  echo 未找到依赖文件。请确认压缩包已完整解压，或运行 Repair Dependencies.cmd。
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)

if not exist "%DATA_DIR%\.env.local" (
  > "%DATA_DIR%\.env.local" echo PINTEREST_CLIENT_ID=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_CLIENT_SECRET=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_REDIRECT_URI=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_ACCESS_TOKEN=
  >> "%DATA_DIR%\.env.local" echo OPENCLAW_SHARED_TOKEN=local-test-token
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_LICENSE_SERVER_URL=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_REQUIRE_REMOTE_LICENSE=true
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_LICENSE_HEARTBEAT_TIMEOUT_MS=10000
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_MANIFEST_URL=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_CHANNEL=stable
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_REQUIRE_SIGNATURE=true
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_PUBLIC_KEY_PATH=license-keys/update-public.pem
)

if not exist "%DATA_DIR%\db.json" (
  copy "%APP_DIR%\packaging\default-db.json" "%DATA_DIR%\db.json" >nul
)

set "MAIN_PORT=%PINTEREST_AUTO_PORT%"
if "%MAIN_PORT%"=="" set "MAIN_PORT=3000"
set /a TRY_PORT=%MAIN_PORT%

:check_port
powershell -NoProfile -ExecutionPolicy Bypass -Command "if (Get-NetTCPConnection -LocalPort !TRY_PORT! -State Listen -ErrorAction SilentlyContinue) { exit 0 } else { exit 1 }" >nul 2>nul
if errorlevel 1 goto port_free
set /a TRY_PORT+=1
set /a MAX_PORT=%MAIN_PORT%+20
if !TRY_PORT! GTR !MAX_PORT! (
  echo.
  echo 3000-3020 端口都被占用，请关闭旧的 Pinterest AI Operator 后重试。
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)
goto check_port

:port_free
set "MAIN_PORT=!TRY_PORT!"

echo.
echo Pinterest AI Operator 正在启动...
echo 日志文件：%LOG_DIR%\pinterest-auto.log
echo 数据目录：%DATA_DIR%
echo 访问地址：http://127.0.0.1:%MAIN_PORT%
echo.

start "Pinterest AI Operator Server" /min cmd /c ""%~dp0Run Server.cmd" "%MAIN_PORT%""
timeout /t 4 /nobreak >nul
start "" "http://127.0.0.1:%MAIN_PORT%"

echo 已打开浏览器。如果页面暂时无法访问，请等待几秒后刷新。
echo 首次使用请填写 Web 云端授权地址和 License Key。
echo 后续升级只需替换程序目录，%DATA_DIR% 会保留授权和业务数据。
echo.
if /I not "%NO_PAUSE%"=="/silent" pause
