from pathlib import Path
from typing import List

import tox

req_path = Path("requirements")

header = """\
#
# This file is autogenerated by tox-constraints
# It is updated every time tox runs
#
"""


def _patch_envconfigs(envconfigs):
    for envconfig in envconfigs.values():
        envconfig.install_command.append("-cconstraints.txt")
        if envconfig.skip_install is True:
            pass
        elif envconfig.skip_install is False:
            envconfig.install_command.append(
                "-r" + str(req_path / "install_requires.txt")
            )
        else:
            raise ValueError


def _export_deps(envconfigs):
    if not req_path.exists():
        req_path.mkdir()

    tox_path = req_path / "tox"
    if not tox_path.exists():
        tox_path.mkdir()

    deps: List[str] = []
    for name, envconfig in envconfigs.items():
        filepath = tox_path / f"{name}.txt"

        with filepath.open("w") as fp:
            for dep in envconfig.deps:
                fp.write(header)
                fp.write(f"{dep}\n")

        deps.append("-r" + str(filepath.relative_to(req_path)))

    with (req_path / "tox.txt").open("w") as fp:
        fp.write(header)
        for dep in deps:
            fp.write(f"{dep}\n")


@tox.hookimpl
def tox_configure(config):
    _patch_envconfigs(config.envconfigs)
    _export_deps(config.envconfigs)

    return None
