#!/usr/bin/env python
"""Generate *.txt (e.g., requirements.txt) files from pyproject.toml."""

import sys
from pathlib import Path
from typing import List

try:  # standard module since Python 3.11
  import tomllib as toml
except ImportError:
  try:  # available for older Python via pip
    import tomli as toml
  except ImportError:
    sys.exit("Please install `tomli` first: `pip install tomli`")

script_pth = Path(__file__)
repo_dir = script_pth.parent.parent
script_relpth = script_pth.relative_to(repo_dir)
header = [
    f"# Generated via {script_relpth.as_posix()}.",
    "# Do not edit this file; modify pyproject.toml instead.",
]


def generate_requirement_file(name: str, req_list: List[str]) -> None:
  req_fname = repo_dir / f"{name}.txt"
  req_fname.write_text("\n".join(header + req_list) + "\n")


def main(name: str = "requirements_default") -> None:
  pyproject = toml.loads((repo_dir / "pyproject.toml").read_text())

  generate_requirement_file(name, pyproject["project"]["dependencies"])


if __name__ == "__main__":
  if len(sys.argv) == 1:
    main()
  elif len(sys.argv) == 2:
    main(sys.argv[1])
  else:
    raise RuntimeError("Too many arguments")
