import pathlib
import tomllib


def generate_requirements_file(
    repo_dir: pathlib.Path, name: str, req_list: list[str], header: list[str]
) -> None:
    """
    Generate a requirements file located under <repo_dir>/requirements/<name>.txt.

    Args:
        repo_dir (Path): the root of the repository.
        name (str): the name of the file to save.
        req_list (list[str]): the list of requirements.
        header (list[str]): the header for the files (may be empty).
    """
    req_list = sorted(req_list)
    req_root = repo_dir / "requirements"
    req_root.mkdir(exist_ok=True, parents=True)
    req_fname = req_root / f"{name}.txt"
    req_fname.write_text(
        "\n".join(header + req_list) + "\n", encoding="utf-8", newline="\n"
    )


def main() -> None:
    """Generate the requirements files for each dependency list in pyproject.toml."""
    script_path = pathlib.Path(__file__)
    repo_dir = script_path.parent.parent
    script_relative = script_path.relative_to(repo_dir)
    header = [
        f"# Generated via {str(script_relative.as_posix())} and pre-commit hook.",
        "# Do not edit this file; modify pyproject.toml instead.",
    ]

    pyproject = tomllib.loads((repo_dir / "pyproject.toml").read_text(encoding="utf-8"))

    generate_requirements_file(
        repo_dir, "default", pyproject["project"]["dependencies"], header
    )

    default_deps = pyproject["project"]["dependencies"]

    for key, opt_list in pyproject["project"]["optional-dependencies"].items():
        generate_requirements_file(repo_dir, key, default_deps + opt_list, header)


if __name__ == "__main__":
    main()
