#!./.venv/bin/python
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from zipfile import ZipFile

import toml


def get_version(cwd: Path) -> str:
    cargo_toml = (cwd / "Cargo.toml").open()
    return toml.load(cargo_toml)["package"]["version"]


def main() -> None:
    cwd = Path(__file__).parent.parent

    version = get_version(cwd)

    dist_dir = cwd / "dist"
    try:
        shutil.rmtree(dist_dir)
    except FileNotFoundError:
        pass

    subprocess.check_call(["./.venv/bin/maturin", "build"], cwd=cwd)
    subprocess.check_call(
        [
            "docker",
            "run",
            "--rm",
            "-v",
            f"{cwd.absolute()}:/io",
            "cdignam/markdown-html-finder-builder:0.3.0",
            "build",
            "--release",
        ],
        cwd=cwd,
    )

    for wheel_path in (cwd / "target" / "wheels").glob("*.whl"):
        if f"markdown_html_finder-{version}" not in str(wheel_path):
            continue
        with tempfile.TemporaryDirectory() as dirpath:
            subprocess.check_call(
                ["./.venv/bin/wheel", "unpack", "--dest", dirpath, wheel_path], cwd=cwd
            )

            unpack_dir = os.path.join(dirpath, f"markdown_html_finder-{version}")

            print("adding type stubs to wheel")
            subprocess.check_call(
                ["cp", "-R", "./py_src/markdown_html_finder", unpack_dir], cwd=cwd
            )

            dist_dir.mkdir(exist_ok=True)
            subprocess.check_call(
                ["./.venv/bin/wheel", "pack", "--dest", dist_dir, unpack_dir], cwd=cwd
            )

        output_wheel = dist_dir / wheel_path.name
        assert output_wheel.exists()

        # smoke test to ensure we added the type stubs
        zip_files = {Path(x).name for x in ZipFile(output_wheel).namelist()}
        for path in (cwd / "py_src/markdown_html_finder").glob("*"):
            assert str(path.name) in zip_files, f"{path} not found in {zip_files}"

    subprocess.check_call(
        ["./.venv/bin/twine", "upload", "--skip-existing", *dist_dir.glob("*.whl")],
        cwd=cwd,
    )


if __name__ == "__main__":
    main()
