#!/usr/bin/env python
"""_project.py - auto-generated by softnanotools."""
import subprocess
from typing import List, Union
from pathlib import Path
from . import _package

from softnanotools.logger import Logger

logger = Logger(__name__)

ASSETS = Path(__file__).parent / "assets"


def execute_template(fname: str, **kwargs) -> str:
    """Takes template from ASSETS folder and formats it with arguments"""
    # copy template from assets folder
    with open(ASSETS / f"{fname}.template", "r") as f:
        result = f.read()
        result = result.format(**kwargs)
    return result


def write_template(folder: Union[str, Path], fname: str, content: str):
    """Writes template to file in a project directory"""
    # create folder if it doesn't exist
    folder.mkdir(parents=True, exist_ok=True)
    # write target file to dest
    with open(folder / fname, "w") as f:
        # write templated version with {subs} substitution rules
        f.write(content)


def generate(
    name,
    packages: List[str] = None,
    modules: List[str] = None,
    dry_run: bool = False,
    pre_commit: bool = False,
    pip_install: bool = False,
    root=None,
):

    templates = {}

    # create folder with random string
    if root is None:
        root = Path(name)
    root.mkdir(exist_ok=True)

    # create main package
    _package.generate(root / name, modules=modules, packages=packages)

    # create test package
    _package.generate(root / 'test', modules=[f"test_{name}"])

    # create list of files to generate
    filenames = [
        "setup.py", "README.md", "setup.cfg", "_version.py", "MANIFEST.in",
        ".gitignore", "pyproject.toml", "quick-build.yml", "coverage.yml",
        "versioneer.py", '.gitattributes'
    ]

    if pre_commit:
        filenames.append(".pre-commit-config.yaml")

    folders = {
        '_version.py': root / name,
        'quick-build.yml': root / '.github' / 'workflows',
        'coverage.yml': root / '.github' / 'workflows',
    }

    # loop over files
    for fname in filenames:
        # get templated string to write
        templates[fname] = execute_template(fname, name=name)

        # add debug statement
        logger.debug(templates[fname])

        # write template to file
        write_template(
            folders.get(fname,
                        root),  # use root folder if custom not specified
            fname,
            templates[fname])

    if not dry_run:

        if pip_install:
            subprocess.run(["pip", "install", "-e", name])

        # Initialise git repo with "main" as default branch
        try:
            subprocess.run(["git", "init"], cwd=root)
        except Exception:
            logger.warning(
                "Running git failed, skipping all git steps by default, next "
                "time use `--dry-run to avoid this warning!"
            )
            return
        try:
            subprocess.run(['git', 'branch', '-M', 'main'], cwd=root)
        except Exception:
            logger.warning(
                "`git init` worked, but `git branch -M main` failed, consider"
                " upgrading your version of git! Continuing to add files and "
                "make first commit."
            )
            return



        if pre_commit:
            try:
                subprocess.run(["pre-commit", "install"], cwd=root)
            except Exception:
                logger.kill(
                    "`pre-commit install` failed, please reinstall "
                    "pre-commit with pip install pre-commit or remove "
                    "the --pre-commit flag!"
                )

        subprocess.run(["git", "add", "."], cwd=root)
        subprocess.run([
            "git", "commit", "-a", "-m",
            f"'First commit for {name} by softnanotools!'"
        ], cwd=root)

    return


if __name__ == "__main__":
    import doctest
    doctest.testmod()
