import os
import logging
import argparse
import json

import jbussdieker

from jbussdieker.config import Config
from jbussdieker.logging import setup_logging
from jbussdieker.templates import PYPROJECT_TEMPLATE, LICENSE_TEMPLATE


def _get_parser():
    parser = argparse.ArgumentParser(description="CLI for jbussdieker")
    parser.add_argument(
        "-v", "--verbose", action="store_true", help="Enable verbose logging"
    )
    subparsers = parser.add_subparsers(dest="command", help="Subcommands")
    subparsers.add_parser("version", help="Show the version")
    parser_config = subparsers.add_parser("config", help="Show or set config")
    parser_config.add_argument("--set", metavar="KEY=VALUE", help="Set a config value")
    parser_create = subparsers.add_parser(
        "create", help="Create a new project directory"
    )
    parser_create.add_argument("name", metavar="NAME", help="Name of the new project")
    return parser


def main(argv=None):
    parser = _get_parser()
    args = parser.parse_args(argv)
    cfg = Config.load()
    log_level = logging.DEBUG if args.verbose else getattr(logging, cfg.log_level)
    setup_logging(level=log_level, format=cfg.log_format)
    logging.debug("Parsed args: %s", args)
    if args.command == "version":
        logging.info(f"jbussdieker v{jbussdieker.__version__}")
    elif args.command == "config":
        if args.set:
            key, sep, value = args.set.partition("=")
            if not sep:
                logging.error("Invalid format. Use KEY=VALUE.")
                return
            if hasattr(cfg, key):
                attr = getattr(cfg, key)
                if isinstance(attr, bool):
                    value = value.lower() in ("1", "true", "yes")
                setattr(cfg, key, value)
                cfg.save()
                logging.info(f"Set {key} = {value}")
            else:
                cfg.custom_settings[key] = value
                cfg.save()
                logging.info(f"Set custom setting {key} = {value}")
        else:
            logging.info("Current config:")
            logging.info(json.dumps(cfg.asdict(), indent=2))
    elif args.command == "create":
        project_name = args.name
        if os.path.exists(project_name):
            logging.error(f"Directory '{project_name}' already exists.")
            return
        os.makedirs(project_name)
        src_dir = os.path.join(project_name, "src", project_name)
        os.makedirs(src_dir)
        tests_dir = os.path.join(project_name, "tests")
        os.makedirs(tests_dir)
        with open(os.path.join(project_name, "pyproject.toml"), "w") as f:
            f.write(PYPROJECT_TEMPLATE.substitute(project_name=project_name))
        with open(os.path.join(project_name, "LICENSE.txt"), "w") as f:
            f.write(LICENSE_TEMPLATE.substitute(project_name=project_name))
        with open(os.path.join(project_name, "README.md"), "w") as f:
            f.write(f"# {project_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"
            )
        logging.info(f"Created new project at: {os.path.abspath(project_name)}")
    else:
        parser.print_help()
