@echo off
setlocal enabledelayedexpansion

:: ============================================================
::  TolingClaw 桌面启动器
::  - 未运行 → 启动
::  - 已运行 → 重启
::  - 自动打开浏览器
:: ============================================================

:: 检查 Node.js
where node >nul 2>nul
if %errorlevel% neq 0 (
    echo [错误] 未检测到 Node.js，请先安装
    pause
    exit /b 1
)

set "BIN_DIR=%~dp0"
set "PKG_DIR=%BIN_DIR%.."
set "PORT=3000"

:: 检查端口是否被 tolingclaw/node 占用
set KILLED=
for /f "tokens=5" %%a in ('netstat -ano 2^>nul ^| findstr ":%PORT%" ^| findstr "LISTENING"') do (
    for /f "tokens=1" %%p in ('wmic process where "ProcessId=%%a" get ExecutablePath 2^>nul ^| findstr /i "node"') do (
        taskkill /F /T /PID %%a >nul 2>nul
        set KILLED=1
    )
)

if defined KILLED (
    echo 正在重启 TolingClaw...
    timeout /t 2 /nobreak >nul
)

echo 正在启动 TolingClaw...
start "TolingClaw" /B node "%PKG_DIR%\bin\tolingclaw.js" gateway dev

:: 等待服务就绪（最多15秒）
for /l %%i in (1,1,15) do (
    netstat -ano 2^>nul | findstr ":%PORT%" | findstr "LISTENING" >nul 2>nul
    if !errorlevel! equ 0 (
        goto :ready
    )
    timeout /t 1 /nobreak >nul
)

:ready
start http://localhost:%PORT%
exit
