from __future__ import annotations

import os
import re
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
APP_INFO = ROOT / "app_info.py"
ISS_TEMPLATE = ROOT / "installer" / "niumasoftware.iss"
ISS_OUT = ROOT / "installer" / "niumasoftware.generated.iss"


def read_version() -> str:
    text = APP_INFO.read_text(encoding="utf-8")
    m = re.search(r"""__VERSION__\s*=\s*["']([^"']+)["']""", text)
    if not m:
        raise RuntimeError("未在 app_info.py 中找到 __VERSION__")
    return m.group(1).strip()


def generate_iss(version: str) -> str:
    tpl = ISS_TEMPLATE.read_text(encoding="utf-8")
    if "{#AppVersion}" not in tpl:
        raise RuntimeError("niumasoftware.iss 未包含 {#AppVersion} 占位符")
    header = f'#define AppVersion "{version}"\n'
    # 如果模板里已经有 #define，则保留并在最前面插入（避免影响原结构）
    return header + tpl


def main() -> int:
    version = read_version()
    out_text = generate_iss(version)
    ISS_OUT.write_text(out_text, encoding="utf-8", newline="\n")
    print(f"generated: {ISS_OUT}")
    print(f"version: {version}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

