#!/usr/bin/env python3
"""Generate a PyInstaller version-info file for ProxyChainManager.exe.

Usage:
    python scripts/generate_version_info.py --version 1.2.3 --out build/version_info.txt

The output is consumed by ProxyChainManager.spec when the file exists.
"""
from __future__ import annotations

import argparse
import re
from pathlib import Path


def _parse_version(version: str) -> tuple[int, int, int, int]:
    parts = re.findall(r"\d+", version)
    nums = [int(x) for x in parts[:4]]
    while len(nums) < 4:
        nums.append(0)
    return nums[0], nums[1], nums[2], nums[3]


def build_version_info(version: str, commit: str = "") -> str:
    filevers = prodvers = _parse_version(version)
    commit_suffix = f" ({commit})" if commit else ""
    return f"""# UTF-8
# Generated by scripts/generate_version_info.py - do not edit by hand.
VSVersionInfo(
  ffi=FixedFileInfo(
    filevers={filevers},
    prodvers={prodvers},
    mask=0x3f,
    flags=0x0,
    OS=0x40004,
    fileType=0x1,
    subtype=0x0,
    date=(0, 0)
  ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'040904B0',
        [StringStruct(u'CompanyName', u'Proxy God'),
        StringStruct(u'FileDescription', u'Proxy God - multi-hop proxy chain manager'),
        StringStruct(u'FileVersion', u'{version}{commit_suffix}'),
        StringStruct(u'InternalName', u'ProxyChainManager'),
        StringStruct(u'LegalCopyright', u'MIT License'),
        StringStruct(u'OriginalFilename', u'ProxyChainManager.exe'),
        StringStruct(u'ProductName', u'Proxy God'),
        StringStruct(u'ProductVersion', u'{version}{commit_suffix}')])
      ]
    ),
    VarFileInfo([VarStruct(u'Translation', [1033, 1200])])
  ]
)
"""


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--version", required=True)
    ap.add_argument("--commit", default="")
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(build_version_info(args.version, args.commit), encoding="utf-8")
    print(f"Wrote {out}")


if __name__ == "__main__":
    main()
