#!/usr/bin/env python3
import sys
import argparse
import shutil
from pathlib import Path
import live_agent

__all__ = []

MODULES_DIRNAME = "modules"
TEMPLATES_DIRNAME = "templates"
TOOLS_DIRNAME = "tools"
SETTINGS_FILENAME = "settings.json"
README_FILENAME = "README.md"
DEV_REQUIREMENTS = "dev-requirements.txt"
PYPROJECT = "pyproject.toml"
PRECOMMIT = ".pre-commit-config.yaml"


def parse_arguments(argv):
    parser = argparse.ArgumentParser(description="Bootstraps a new agent")
    args = parser.parse_args(argv[1:])

    return args


def find_templates_dir():
    lib_path = Path(live_agent.__file__)
    lib_root = lib_path.parent
    return lib_root.joinpath(TEMPLATES_DIRNAME)


if __name__ == "__main__":
    """
    Command which bootstraps an agent, adding the following:
    - `README.md`
    - `settings.json` with the basic structure
    - `tools` folder (same as `live-agent`'s)
    - `modules` folder, containing an `__init__.py` file
    - `dev-requirements.txt`
    """

    args = parse_arguments(sys.argv)
    templates_dir = find_templates_dir()

    print("Creating the agent files:")
    print(f'- Creating "{README_FILENAME}"')
    shutil.copy2(templates_dir.joinpath(README_FILENAME), README_FILENAME)

    print(f'- Creating "{SETTINGS_FILENAME}"')
    shutil.copy2(templates_dir.joinpath(SETTINGS_FILENAME), SETTINGS_FILENAME)

    if Path(TOOLS_DIRNAME).exists():
        print(f'- Removing old folder "{TOOLS_DIRNAME}"')
        shutil.rmtree(TOOLS_DIRNAME, ignore_errors=True)

    print(f'- Creating folder "{TOOLS_DIRNAME}"')
    shutil.copytree(templates_dir.joinpath(TOOLS_DIRNAME), TOOLS_DIRNAME)

    print(f'- Creating folder "{MODULES_DIRNAME}"')
    Path(MODULES_DIRNAME).mkdir(exist_ok=True)

    print(f'- Creating "{MODULES_DIRNAME}/__init__.py"')
    Path(f"{MODULES_DIRNAME}/__init__.py").touch(exist_ok=True)

    print("Adding project settings:")
    print(f'- Creating "{DEV_REQUIREMENTS}"')
    shutil.copy2(templates_dir.joinpath(DEV_REQUIREMENTS), DEV_REQUIREMENTS)

    print(f'- Creating "{PYPROJECT}"')
    shutil.copy2(templates_dir.joinpath(PYPROJECT), PYPROJECT)

    print(f'- Creating "{PRECOMMIT}"')
    shutil.copy2(templates_dir.joinpath(PRECOMMIT), PRECOMMIT)

    print("done")
