#!/usr/bin/env python3
"""Build the one-file Astitvaams Print Helper for whichever OS this runs on.

PyInstaller cannot cross-compile, so each platform builds its own: run this on
Windows for the .exe, on macOS for the .app, on Linux for the binary. The
GitHub workflow in .github/workflows does exactly that on three runners.

    python3 build.py
"""
import platform
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
NAME = "Astitvaams-Print-Helper"
SYSTEM = platform.system()


def main() -> int:
    dist = HERE / "dist"
    shutil.rmtree(dist, ignore_errors=True)
    shutil.rmtree(HERE / "build", ignore_errors=True)

    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--onefile",
        "--name", NAME,
        "--clean", "--noconfirm",
        # setup_ui and selfinstall are imported lazily inside functions, so
        # PyInstaller's static analysis does not see them.
        "--hidden-import", "setup_ui",
        "--hidden-import", "selfinstall",
        "--collect-all", "brother_ql",
        # Pillow pulls in tkinter otherwise, which is not installed everywhere
        # and is not used — it would fail the build for no gain.
        "--exclude-module", "tkinter",
        "--exclude-module", "PIL.ImageTk",
    ]

    if SYSTEM == "Windows":
        # No console window: double-clicking should open the browser, not a
        # black box the user then closes and kills the helper with.
        cmd += ["--windowed"]
        icon = HERE / "icon.ico"
        if icon.exists():
            cmd += ["--icon", str(icon)]
    elif SYSTEM == "Darwin":
        cmd += ["--windowed", "--osx-bundle-identifier", "com.astitva.ams-print-helper"]
        icon = HERE / "icon.icns"
        if icon.exists():
            cmd += ["--icon", str(icon)]
    # Linux keeps its console: it is normally launched from a terminal or the
    # service, and a silent failure there is worse than a visible one.

    cmd.append(str(HERE / "ams_print_helper.py"))

    print(f"Building for {SYSTEM}…")
    r = subprocess.run(cmd, cwd=HERE)
    if r.returncode != 0:
        return r.returncode

    built = sorted(dist.glob("*"))
    print("\nBuilt:")
    for b in built:
        size = b.stat().st_size / 1_048_576 if b.is_file() else 0
        print(f"  {b.name}" + (f"  ({size:.0f} MB)" if size else "  (app bundle)"))
    return 0


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