#!/usr/bin/env python

import os
import sys

try:
    import rtoml as toml
except ImportError:
    print('Please install `rtoml` first: `pip install rtoml`')
    sys.exit(1)


if not os.path.isfile('pyproject.toml'):
    print('Please run this script from the skimage repository root:')
    print('  python tools/generate_pyproject.toml.py')
    sys.exit(1)


def parse_requirements_file(filename):
    with open(filename) as fid:
        requires = [l.strip() for l in fid.readlines() if not l.startswith("#")]
        requires = [l for l in requires if l]

    return requires


with open('tools/pyproject.toml.in') as f:
    pyproject = toml.load(f)

pyproject['project']['dependencies'] = \
   parse_requirements_file("requirements/default.txt")

pyproject['project']['optional-dependencies'] = {
   dep: parse_requirements_file(f"requirements/{dep}.txt")
   for dep in ["build", "data", "default", "developer", "docs", "optional", "test"]
}

banner = f"""\
{"#" * 80}
# DO NOT EDIT
# AUTOGENERATED BY
#
#     $ python tools/generate_pyproject.toml.py
#
# EDIT tools/pyproject.toml.in AND RUN THAT SCRIPT.
#
{"#" * 80}

"""

with open('pyproject.toml', 'w') as f:
    f.write(banner)
    toml.dump(pyproject, f, pretty=True)
