import re
import zipfile
from pathlib import Path


def pdm_build_initialize(context):
    context.ensure_build_dir()


def pdm_build_finalize(context, artifact):
    pth_artifact = Path(artifact)

    if pth_artifact.suffix == ".whl":
        delete_source_files_from_wheel(pth_artifact)


def delete_source_files_from_wheel(pth_to_whl: Path):
    assert pth_to_whl.exists(), "wheel file not existing"
    tmp_dir = pth_to_whl.parent / "tmp"
    tmp_dir.mkdir()
    filename = pth_to_whl.name
    tmp_whl = tmp_dir / filename
    pattern = re.compile(r".*\.c$|.*detection.py$|.*\.pyi$")

    with zipfile.ZipFile(pth_to_whl, mode="r") as src:
        with zipfile.ZipFile(tmp_whl, mode="w") as dst:
            for filename in src.namelist():
                if pattern.match(filename) is None:
                    data = src.read(filename)
                    dst.writestr(filename, data)

    tmp_whl.replace(pth_to_whl)
    tmp_dir.rmdir()
