#!/bin/python3

import re
import shutil
import subprocess
import sys
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from pathlib import Path
from typing import NamedTuple, cast

assert __name__ == "__main__"


class Target(NamedTuple):
    target: str
    compat: list[str] | None


TARGETS: list[Target] = [
    Target("x86_64-unknown-linux-musl", ["manylinux_2_17", "musllinux_1_1"]),
    Target("aarch64-unknown-linux-musl", ["manylinux_2_17", "musllinux_1_1"]),
]

CWD = Path(".")
WORKSPACE = Path(__file__).parent
_text = (WORKSPACE / "Cargo.toml").read_text()
PKG_NAME = cast("re.Match[str]", re.search(r'name = "(.+)"', _text))[1]
PKG_VERSION = cast("re.Match[str]", re.search(r'version = "(.+)"', _text))[1]
del _text

DEFAULT_OUT_DIR = CWD / "dist" / PKG_VERSION


cli_parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
cli_parser.add_argument(
    "--output-dir", "-o", type=Path, default=DEFAULT_OUT_DIR, help="output directory"
)
cli_parser.add_argument("--bin", action="store_true", help="include binares")
cli_parser.add_argument("--clear", action="store_true", help="delete old files in output directory")
cli = cli_parser.parse_args()

OUT_DIR = cast("Path", cli.output_dir)
PYPI_OUT_DIR = OUT_DIR / "pypi"
INCLUDE_BIN = cast("bool", cli.bin)
CLEAR = cast("bool", cli.clear)

if CLEAR and OUT_DIR.exists():
    assert OUT_DIR.is_dir()
    shutil.rmtree(OUT_DIR)

OUT_DIR.mkdir(parents=True, exist_ok=True)

subprocess.check_call(("uv", "sync", "--no-install-project"))

cmd = ("uv", "build", "--sdist", "--no-create-gitignore", "--out-dir", PYPI_OUT_DIR)
print("\n---\nrun: `{}`".format(" ".join(map(str, cmd))), flush=True)
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
assert proc.stderr is not None

sdist_path: Path | None = None

for line in proc.stderr:
    line = line.decode(errors="ignore")
    sys.stderr.write(line)
    if line.rstrip().startswith("Successfully built"):
        sdist_path = Path(line.rstrip().split(maxsplit=2)[-1])

if (rc := proc.wait()) != 0:
    raise subprocess.CalledProcessError(rc, cmd)

if sdist_path is None:
    print("warning: cannot parse sdist path", flush=True)
else:
    subprocess.call(("tar", "-tvf", sdist_path))


for target, compat in TARGETS:
    cmd = [
        "uv",
        "run",
        "--no-sync",
        "maturin",
        "build",
        "--release",
        "--zig",
        "--target",
        target,
        "--out",
        PYPI_OUT_DIR,
    ]
    if compat is not None:
        cmd += ["--compatibility", *compat]

    print("\n---\nrun: `{}`".format(" ".join(map(str, cmd))), flush=True)
    subprocess.check_call(cmd)

    bin_path = CWD / "target" / target / "release" / PKG_NAME

    if INCLUDE_BIN:
        shutil.copy2(bin_path, OUT_DIR / (PKG_NAME + "-" + target.split("-")[0]))

    subprocess.check_call(
        (
            "tar",
            "-czf",
            OUT_DIR / f"{PKG_NAME.replace('-', '_')}-{PKG_VERSION}-{target}.tar.gz",
            "-C",
            bin_path.parent,
            "--owner=0",
            "--group=0",
            PKG_NAME,
        )
    )
