import os.path

import pkg_resources


class Requirements(object):
    """Generate a pip compatible requirements.txt from our working set based on
    the 'bandersnatch' requirement."""

    def __init__(self, buildout, name, options) -> None:
        self.name, self.options = name, options
        options["path"] = os.path.join(
            buildout["buildout"]["directory"], "requirements.txt"
        )

    def install(self):
        path = self.options["path"]
        require = pkg_resources.Requirement.parse("bandersnatch")
        dependencies = pkg_resources.working_set.resolve([require])
        seen = set()
        with open(path, "w") as requirements_txt:
            requirements_txt.write("# Generated by buildout\n")
            for dep in reversed(dependencies):
                dep = dep.as_requirement()
                if dep.key in seen:
                    continue
                seen.add(dep.key)
                requirements_txt.write(str(dep) + "\n")
        return path

    update = install
