#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
本地测试包：与 scripts/package/pack_local_test.bat 相同流程，适合在 PowerShell / CI 中调用。
不修改版本号，输出到 build\output_local\，不覆盖正式 build\output\。
"""
import os
import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
OUTPUT_LOCAL_DIR = ROOT / "build" / "output_local"
ISCC = os.environ.get(
    "INNO_SETUP_ISCC",
    r"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
)


def main() -> int:
    if any(arg in ("-h", "--help") for arg in sys.argv[1:]):
        print("用法: python scripts/package/pack_local_test.py")
        print("生成 build\\output_local\\ServerManager_Setup_LOCAL.exe，不修改正式 build\\output\\。")
        return 0

    build_script = ROOT / "scripts" / "package" / "build.bat"
    if not build_script.exists():
        print("错误: 未找到 scripts\\package\\build.bat", file=sys.stderr)
        return 1
    if not Path(ISCC).is_file():
        print(f"错误: 未找到 Inno Setup 编译器: {ISCC}", file=sys.stderr)
        print("可设置环境变量 INNO_SETUP_ISCC 指向 ISCC.exe", file=sys.stderr)
        return 1

    print("[1/3] PyInstaller: scripts\\package\\build.bat nopause ...")
    # Use cmd /d /c call ... so exit /b propagates.
    r = subprocess.run(
        ["cmd.exe", "/d", "/c", "call", str(build_script), "nopause"],
        cwd=str(ROOT),
        shell=False,
    )
    if r.returncode != 0:
        print("[失败] PyInstaller 步骤退出码:", r.returncode, file=sys.stderr)
        return r.returncode

    print("[2/3] Inno Setup: LOCAL_TEST -> build\\output_local\\ ...")
    r = subprocess.run(
        [ISCC, "/DLOCAL_TEST=1", str(ROOT / "scripts" / "package" / "build_installer.iss")],
        cwd=str(ROOT),
    )
    if r.returncode != 0:
        print("[失败] Inno Setup 退出码:", r.returncode, file=sys.stderr)
        return r.returncode

    out_local = OUTPUT_LOCAL_DIR
    out_local.mkdir(parents=True, exist_ok=True)
    vj = ROOT / "resources" / "version.json"
    if vj.exists():
        shutil.copy2(vj, out_local / "version.json")
        print("[3/3] 已复制 version.json -> build\\output_local\\")

    cleanup_script = ROOT / "scripts" / "package" / "clean_artifacts.py"
    if cleanup_script.exists():
        print("[cleanup] 删除打包中间产物 ...")
        subprocess.run([sys.executable, str(cleanup_script)], cwd=str(ROOT), check=False)

    exe = out_local / "ServerManager_Setup_LOCAL.exe"
    print()
    print("本地测试包:", exe)
    print("验证通过后，再执行正式发版（scripts\\package\\release.bat / scripts\\package\\pack_all.bat + scripts\\package\\release.py）。")
    return 0


if __name__ == "__main__":
    sys.exit(main())
