@echo off
setlocal enabledelayedexpansion
title Animation Manager
chcp 65001 >nul

REM ================关闭旧的 server.js 进程========================
taskkill /F /IM node.exe >nul 2>&1

REM 等待一下确保进程完全关闭
timeout /t 1 /nobreak >nul 2>&1

REM ================启动 server.js（后台运行）========================
start /B node server/server.js

REM 等待一小段时间，让服务器先清屏
timeout /t 1 /nobreak >nul 2>&1

REM ================检测服务器是否启动成功========================
echo [批处理脚本] 正在检测服务器状态...
set MAX_ATTEMPTS=30
set ATTEMPT=0
set SERVER_READY=0

:check_server
set /a ATTEMPT+=1
if %ATTEMPT% GTR %MAX_ATTEMPTS% (
    echo 错误：服务器启动超时，请检查服务器日志
    pause
    exit /b 1
)

REM 使用 PowerShell 检测服务器是否响应（兼容性更好）
powershell -NoProfile -Command "try { $response = Invoke-WebRequest -Uri 'http://localhost:3000/' -TimeoutSec 2 -UseBasicParsing -ErrorAction Stop; exit 0 } catch { exit 1 }" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    set SERVER_READY=1
) else (
    REM 如果 PowerShell 方法失败，尝试简单的端口检测
    powershell -NoProfile -Command "try { $tcpClient = New-Object System.Net.Sockets.TcpClient; $tcpClient.Connect('localhost', 3000); $tcpClient.Close(); exit 0 } catch { exit 1 }" >nul 2>&1
    if %ERRORLEVEL% EQU 0 (
        set SERVER_READY=1
    )
)

if %SERVER_READY% EQU 0 (
    timeout /t 1 /nobreak >nul 2>&1
    goto check_server
)

REM ================服务器已启动，打开浏览器========================
REM 等待服务器输出完成后再显示消息
timeout /t 1 /nobreak >nul 2>&1
start http://localhost:3000/index.html?auto=true

REM 不再输出额外信息，避免与服务器输出重叠
pause >nul

REM 关闭 node 服务
taskkill /F /IM node.exe >nul 2>&1
