@echo off
title 语音问答助手
cd /d "%~dp0"

REM ===== 1. 确保 WorkBuddy 运行 =====
tasklist 2>nul | findstr /i "WorkBuddy.exe" >nul
if errorlevel 1 (
    if exist "C:\Program Files\WorkBuddy\WorkBuddy.exe" start "" "C:\Program Files\WorkBuddy\WorkBuddy.exe"
    timeout /t 8 /nobreak >nul
)

REM ===== 2. 确保网关在运行（端口 7890，用 WorkBuddy 自带 CLI 官方 serve 模式）=====
REM 先定位 Node（本目录免安装版优先），网关 CLI 是 Node 脚本，必须用 node 运行
set "NODE="
if exist "%~dp0node.exe" set "NODE=%~dp0node.exe"
if not defined NODE where node >nul 2>nul && set "NODE=node"
netstat -ano 2>nul | findstr ":7890" | findstr "LISTENING" >nul
if errorlevel 1 (
    set "CLI="
    set "CLI_IS_SCRIPT="
    if exist "C:\Program Files\WorkBuddy\resources\app.asar.unpacked\cli\bin\codebuddy" (
        set "CLI=C:\Program Files\WorkBuddy\resources\app.asar.unpacked\cli\bin\codebuddy"
        set "CLI_IS_SCRIPT=1"
    )
    if not defined CLI if exist "C:\Program Files (x86)\WorkBuddy\resources\app.asar.unpacked\cli\bin\codebuddy" (
        set "CLI=C:\Program Files (x86)\WorkBuddy\resources\app.asar.unpacked\cli\bin\codebuddy"
        set "CLI_IS_SCRIPT=1"
    )
    if not defined CLI where codebuddy >nul 2>nul && set "CLI=codebuddy"
    if defined CLI (
        REM codebuddy 是无扩展名的 Node 脚本，必须用 node 执行；PATH 中的可执行文件则直接运行
        if defined CLI_IS_SCRIPT (
            start "WorkBuddy-Gateway" "%NODE%" "%CLI%" --serve --port 7890
        ) else (
            start "WorkBuddy-Gateway" "%CLI%" --serve --port 7890
        )
        timeout /t 6 /nobreak >nul
    ) else (
        echo [提示] 未找到 codebuddy 命令行，请确认 WorkBuddy 安装完整。
    )
)

REM ===== 3. 确保代理在运行（端口 6800）=====
if not defined NODE (
    set "NODE="
    if exist "%~dp0node.exe" set "NODE=%~dp0node.exe"
    if not defined NODE where node >nul 2>nul && set "NODE=node"
)
if not defined NODE (
    echo [ERROR] Node.js not found.
    echo 请把 node.exe 放到本文件夹，或安装 Node.js。
    echo.
    pause
    exit /b 1
)
netstat -ano 2>nul | findstr ":6800" | findstr "LISTENING" >nul
if errorlevel 1 (
    start "WorkBuddy-Bridge" "%NODE%" "%~dp0gateway-bridge.js"
)

REM ===== 4. 打开网页 =====
timeout /t 3 /nobreak >nul
start "" "http://localhost:6800"

echo.
echo 语音问答助手已启动，网页即将打开。
echo 如果显示"未连接"，请稍等 10 秒，会自动重连。
echo.
pause
