import os
import logging

from jbussdieker.templates import (
    MAKEFILE_TEMPLATE,
    PYPROJECT_TEMPLATE,
    LICENSE_TEMPLATE,
    WORKFLOW_TEMPLATE,
    WORKFLOW_PUBLISH_SCRIPT,
    TEST_TEMPLATE,
    GITIGNORE,
)


class ProjectGenerator:
    def __init__(self, name):
        self.name = name

    def run(self):
        if os.path.exists(self.name):
            logging.error(f"Directory '{self.name}' already exists.")
            return
        os.makedirs(self.name)
        gh_workflow_dir = os.path.join(self.name, ".github", "workflows")
        os.makedirs(gh_workflow_dir)
        src_dir = os.path.join(self.name, "src", self.name)
        os.makedirs(src_dir)
        tests_dir = os.path.join(self.name, "tests")
        os.makedirs(tests_dir)
        with open(os.path.join(self.name, "Makefile"), "w") as f:
            f.write(MAKEFILE_TEMPLATE.replace("%PROJECT_NAME%", self.name))
        with open(os.path.join(self.name, ".gitignore"), "w") as f:
            f.write(GITIGNORE)
        with open(os.path.join(gh_workflow_dir, "ci.yml"), "w") as f:
            f.write(WORKFLOW_TEMPLATE.replace("%PROJECT_NAME%", self.name))
        with open(os.path.join(gh_workflow_dir, "publish.yml"), "w") as f:
            f.write(WORKFLOW_PUBLISH_SCRIPT)
        with open(os.path.join(self.name, "pyproject.toml"), "w") as f:
            f.write(PYPROJECT_TEMPLATE.substitute(project_name=self.name))
        with open(os.path.join(self.name, "LICENSE"), "w") as f:
            f.write(LICENSE_TEMPLATE.substitute(project_name=self.name))
        with open(os.path.join(self.name, "README.md"), "w") as f:
            f.write(f"# {self.name}\n\nGenerated by jbussdieker.\n")
        with open(os.path.join(src_dir, "__init__.py"), "w") as f:
            f.write('__version__ = "0.0.0"\n')
        with open(os.path.join(src_dir, "cli.py"), "w") as f:
            f.write(
                "def main():\n    print('Hello!')\n\n\nif __name__ == '__main__':\n    main()\n"
            )
        with open(os.path.join(tests_dir, "__init__.py"), "w") as f:
            f.write("")
        with open(os.path.join(tests_dir, f"test_{self.name}.py"), "w") as f:
            f.write(TEST_TEMPLATE.substitute(project_name=self.name))
        logging.info(f"Created new project at: {os.path.abspath(self.name)}")
