import sys
from pathlib import Path

from packaging.utils import parse_wheel_filename

from uv_pack._process import exit_on_error, run_cmd


def build_src_wheel(*, source_path: Path, out_path: Path, other_args: str) -> None:
    cmd = [
        "uv",
        "build",
        str(source_path),
        "--wheel",
        "--out-dir",
        str(out_path),
    ]

    cmd.extend(other_args.split())
    exit_on_error(run_cmd(cmd, "uv build"))


def build_requirements(
    *,
    requirements_txt: Path,
    requirements_export_txt: Path,
    vendor_directory: Path,
) -> None:
    vendor_pins: list[str] = []

    for wheel in vendor_directory.glob("*.whl"):
        name, version, *_ = parse_wheel_filename(wheel.name)
        vendor_pins.append(f"{name}=={version}")

    header = "\n".join(
        [
            "# This file was autogenerated by uv-pack via the following command:",
            f"#    uv-pack {' '.join(sys.argv[1:])}",
            *sorted(set(vendor_pins)),
        ],
    )

    requirements_txt.write_text(
        header + "\n" + requirements_export_txt.read_text(encoding="utf-8"),
        encoding="utf-8",
    )
