"""Generate and publish the UBI diagrams on Windows or Linux."""

import importlib.util
import os
from pathlib import Path
import shutil
import subprocess
import sys


def main():
    source = Path(__file__).resolve().parent
    repo = source.parents[5]
    missing = [name for name in ("numpy", "matplotlib")
               if importlib.util.find_spec(name) is None]
    if missing:
        print("Missing packages: " + ", ".join(missing), file=sys.stderr)
        print(f'Install with: "{sys.executable}" -m pip install numpy matplotlib',
              file=sys.stderr)
        return 1

    environment = os.environ.copy()
    environment.setdefault("MPLBACKEND", "Agg")
    svg_dir = source / "svg"
    svg_dir.mkdir(exist_ok=True)
    subprocess.run([sys.executable, str(source / "emtr.py")], cwd=source,
                   env=environment, check=True)
    from emtr import example_households
    households = [title.replace(" ", "_") for _, title in example_households()]
    expected = [f"{kind}_{household}.svg" for kind in ("emtr", "disp", "etr")
                for household in households]
    missing = [name for name in expected
               if not (svg_dir / name).is_file() or (svg_dir / name).stat().st_size == 0]
    if missing:
        print("Missing generated SVGs: " + ", ".join(missing), file=sys.stderr)
        return 1
    for relative in ("documents/vota/vota-principles/svg",
                     "documents/vota/vota-principles-html/svg"):
        destination = repo / relative
        destination.mkdir(parents=True, exist_ok=True)
        for name in expected:
            shutil.copy2(svg_dir / name, destination / name)
        print(f"Published SVGs to {destination}")
    return 0


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