import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent / "stub-uploader"))


import re
import shlex
import shutil
import subprocess
import tomllib

from stub_uploader.build_wheel import main as build_wheel

debian = Path(".") / "debian"
build_root = debian / "build"
install_root = debian / "python3-typeshed/usr/lib/python3/dist-packages/"
temp_install_root = debian / "temp-python3-typeshed"

install_root.mkdir(parents=True, exist_ok=True)
temp_install_root.mkdir(parents=True, exist_ok=True)


def run(cmd):
    print(shlex.join(cmd))
    subprocess.check_call(cmd)


provides = []
for stub in sys.argv[1:]:
    with open(f"stubs/{stub}/METADATA.toml", 'rb') as fp:
        metadata = tomllib.load(fp)
    version = metadata["version"].replace(".*", "")
    build_dir = build_root / stub
    if build_dir.exists():
        shutil.rmtree(build_dir)
    build_dir.mkdir(parents=True)
    distdir = Path(build_wheel(".", stub, version, build_dir))
    print('The distdir is: {}'.format(distdir))
    for wheel in distdir.glob("*.whl"):
        target = temp_install_root / wheel.name
        cmd = [sys.executable, "-mpip", "install", "--no-deps", f"--target={target}", str(wheel)]
        run(cmd)
        shutil.copytree(target, install_root, dirs_exist_ok=True)
        shutil.rmtree(target)
    virtual_package = "python3-types-" + re.sub(r"[^a-z0-9=]", "-", stub.lower())
    provides.append(f"{virtual_package} (= {version})")

(debian / "python3-typeshed.substvars").write_text("typeshed:Provides=" + ", ".join(provides) + "\n")
