@echo off
chcp 65001 >nul
setlocal

for %%I in ("%~dp0..\..") do set "ROOT=%%~fI"
set "ISCC=C:\Program Files (x86)\Inno Setup 6\ISCC.exe"

title Server Manager - 一键发版

echo(============================================================
echo(         Server Manager - 一键发版
echo(         顺序：PyInstaller 打包 ^> 改版本号并同步 dist ^> Inno ^> 收尾
echo(         默认全量更新，产物统一输出到 build\output
echo(============================================================
echo( 提示：发版前请先打本地测试包验证 ^(scripts\package\pack_local_test.bat^)
echo(============================================================
echo(

set "NEW_VER=%~1"
set "OUTPUT_DIR=%ROOT%\build\output"
if "%NEW_VER%"=="" (
    set /p "NEW_VER=请输入新版本号 (x.y.z，例如 1.0.4): "
)
if "%NEW_VER%"=="" (
    echo([错误] 未输入版本号
    pause
    exit /b 1
)

echo(
echo([阶段 1/4] PyInstaller 打包 ServerManager.exe ...
call "%ROOT%\scripts\package\build.bat" nopause
if errorlevel 1 (
    echo([失败] PyInstaller 打包未成功
    pause
    exit /b 1
)
echo(

echo([阶段 2/4] 更新版本号、全量更新配置并同步 version.json 到 dist ...
python "%ROOT%\scripts\package\release.py" "%NEW_VER%"
if errorlevel 1 (
    echo([失败] 版本号更新失败
    pause
    exit /b 1
)
echo(

echo([阶段 3/4] Inno Setup 编译安装包 ...
if not exist "%ISCC%" goto :missing_iscc
"%ISCC%" "%ROOT%\scripts\package\build_installer.iss"
if errorlevel 1 goto :iscc_failed
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"
if not exist "%OUTPUT_DIR%\patches" mkdir "%OUTPUT_DIR%\patches"
echo(

echo([阶段 4/4] 复制 version.json 至 build\output ...
python "%ROOT%\scripts\package\release.py" --post-build
echo(

echo([清理] 删除打包中间产物 ...
python "%ROOT%\scripts\package\clean_artifacts.py"
echo(

echo(============================================================
echo(一键发版完成！
echo(  新产出目录 build\output\
echo(    - ServerManager_Setup.exe   完整安装包
echo(    - version.json              版本与更新配置
echo(    - patches\*.patch           增量补丁（结构未变时才手动启用）
echo(============================================================
echo(
pause
exit /b 0

:missing_iscc
echo([错误] 未找到 Inno Setup: %ISCC%
pause
exit /b 1

:iscc_failed
echo([失败] Inno Setup 编译未成功
pause
exit /b 1
