"""Package the pinned x64 runtime, portable launcher, Tk and source."""

import argparse
from pathlib import Path
from shutil import copy2, copytree, ignore_patterns
from tempfile import TemporaryDirectory
from zipfile import ZIP_DEFLATED, ZipFile

SOURCE = Path(__file__).resolve().parents[1]


def stage_runtime(destination, args):
    destination.mkdir()
    with ZipFile(args.python) as archive:
        for item in archive.namelist():
            if item.endswith("/") or not item.startswith("tools/"):
                continue
            relative = Path(item).relative_to("tools")
            if relative.parts[0] not in {"Lib", "DLLs"} and len(relative.parts) != 1:
                continue
            if len(relative.parts) >= 3 and relative.parts[1] == "site-packages" and relative.parts[2].startswith("pip"):
                continue
            path = destination / relative
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(archive.read(item))
    with ZipFile(args.vclibs) as redist:
        (destination/"msvcp140.dll").write_bytes(redist.read("msvcp140.dll"))
    copytree(args.tk/"Lib/tkinter", destination/"Lib/tkinter", dirs_exist_ok=True)
    copytree(args.tk/"tcl", destination/"tcl", ignore=ignore_patterns("demos","nmake","*.lib"))
    for name in ("_tkinter.pyd","tcl86t.dll","tk86t.dll","zlib1.dll"):
        copy2(args.tk/"DLLs"/name, destination/"DLLs"/name)
    packages = destination/"Lib/site-packages"
    packages.mkdir(exist_ok=True)
    for name in ("cadquery_ocp_novtk", "numpy", "pillow"):
        files = list(args.wheels.glob(f"{name}-*-cp312-cp312-win_amd64.whl"))
        if len(files) != 1:
            raise ValueError(f"Expected one x64 Python 3.12 wheel for {name}")
        with ZipFile(files[0]) as wheel:
            for item in wheel.namelist():
                if item.endswith("/"):
                    continue
                path = Path(item)
                if path.parts[0].endswith(".data"):
                    if len(path.parts)<3 or path.parts[1] not in {"purelib","platlib"}:
                        raise ValueError(f"Unsupported wheel install scheme: {item}")
                    path = Path(*path.parts[2:])
                target = packages / path
                target.parent.mkdir(parents=True,exist_ok=True)
                contents = wheel.read(item)
                if target.exists() and target.read_bytes() != contents:
                    raise ValueError(f"Wheel paths conflict: {path}")
                target.write_bytes(contents)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("python","tk","wheels","launcher","raster","vclibs","output"):
        parser.add_argument(f"--{name}",type=Path,required=True)
    args=parser.parse_args()
    with TemporaryDirectory() as directory:
        root=Path(directory)
        app=root/"STEPVacuumShell"
        app.mkdir()
        stage_runtime(app/"runtime",args)
        copytree(SOURCE,app/"source",ignore=ignore_patterns("__pycache__","*.so","*.dll","*.bak"))
        copy2(args.raster,app/"source/raster.dll")
        copy2(args.launcher,app/"STEPVacuumShell.exe")
        for name in ("README.md","StepShellConsole.cmd"):
            copy2(SOURCE/name,app/name)
        with ZipFile(args.output,"x",ZIP_DEFLATED,compresslevel=6) as archive:
            for path in sorted(app.rglob("*")):
                if path.is_file():
                    archive.write(path,path.relative_to(root).as_posix())


if __name__=="__main__":
    main()
