@echo off
setlocal enabledelayedexpansion
chcp 936 >nul
cd /d "%~dp0"

rem ============================================================
rem  PlantGame 一键启动
rem    1) 检查文件  2) 起服务端（新窗口）  3) 等服务端监听端口  4) 起客户端（新窗口）
rem  用法：双击即可；也可以带端口参数，例如  一键启动.bat 25600
rem ============================================================

set "PORT=%~1"
if "%PORT%"=="" set "PORT=25566"

echo ============================================
echo   PlantGame 一键启动    端口 %PORT%
echo ============================================
echo.

if not exist "server-1.0.0-all.jar"  goto :nofiles
if not exist "PlantGame2-1.0.0.jar"  goto :nofiles
if not exist "plant-mod-agent.jar"   goto :nofiles
if not exist "启动服务端.bat"          goto :noscripts
if not exist "启动客户端.bat"          goto :noscripts

rem ---- 端口已经在监听就不重复起服务端 ----
set "LISTENING="
for /f "tokens=*" %%a in ('netstat -ano ^| findstr /c:":%PORT%" ^| findstr /c:"LISTENING"') do set "LISTENING=1"

if defined LISTENING (
  echo [1/2] 端口 %PORT% 已经在监听 —— 跳过服务端，直接开客户端
) else (
  echo [1/2] 启动服务端 ...（新窗口，关掉那个窗口即停服^）
  start "PlantGame 服务端" cmd /c ""%~dp0启动服务端.bat" %PORT%"
  echo       等待服务端开始监听 %PORT% ...
  set /a N=0
  call :waitport
)

echo [2/2] 启动客户端 ...（新窗口；它会自动连上次用过的地址^）
echo       如果客户端连的不是本机 %PORT%：在连接界面把地址改成 127.0.0.1:%PORT%
start "PlantGame 客户端" cmd /c ""%~dp0启动客户端.bat""
echo.
echo 完成。桌面上应该有两个窗口：服务端 / 客户端（关掉窗口即退出）。
ping -n 4 127.0.0.1 >nul
exit /b 0

:waitport
set /a N+=1
ping -n 2 127.0.0.1 >nul
netstat -ano | findstr /c:":%PORT%" | findstr /c:"LISTENING" >nul
if not errorlevel 1 (
  echo       服务端已就绪（%N% 秒）
  exit /b 0
)
if %N% lss 30 goto waitport
echo       [警告] 等了 %N% 秒还没监听到 %PORT%，仍然启动客户端
echo               先在服务端窗口看有没有报错（端口被占 / 缺 jar）
exit /b 0

:nofiles
echo [错误] 当前目录缺少游戏文件，需要这些：
echo        server-1.0.0-all.jar / PlantGame2-1.0.0.jar / plant-mod-agent.jar
echo        本脚本要放在游戏根目录（和这些 jar 同级）。
echo.
pause
exit /b 1

:noscripts
echo [错误] 缺少 启动服务端.bat 或 启动客户端.bat，请从发布包补齐。
echo.
pause
exit /b 1