"""Command line tools for managing NavConfig projects."""
from __future__ import annotations

import argparse
import logging
from pathlib import Path
from textwrap import dedent

LOGGER = logging.getLogger(__name__)


DEFAULT_ENV_CONTENT = """\
# Generated by NavConfig
# Update these values to match your environment specifics.
ENV={environment}
DEBUG=true
CONFIG_FILE=etc/config.ini
"""

DEFAULT_CONFIG_CONTENT = """\
[navconfig]
# Default configuration generated by NavConfig.
# Adjust values to match your project requirements.
DEBUG = true
CONFIG_FILE = etc/config.ini
"""


def create_project_structure(env_name: str, project_root: Path) -> dict[str, Path]:
    """Create the default NavConfig project structure."""
    env_directory = project_root / "env" / env_name
    env_directory.mkdir(parents=True, exist_ok=True)

    env_file = env_directory / ".env"
    if not env_file.exists():
        env_file.write_text(DEFAULT_ENV_CONTENT.format(environment=env_name), encoding="utf-8")

    etc_directory = project_root / "etc"
    etc_directory.mkdir(parents=True, exist_ok=True)

    config_file = etc_directory / "config.ini"
    if not config_file.exists():
        config_file.write_text(dedent(DEFAULT_CONFIG_CONTENT), encoding="utf-8")

    return {
        "env_directory": env_directory,
        "env_file": env_file,
        "etc_directory": etc_directory,
        "config_file": config_file,
    }


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="kardex",
        description="Utilities for bootstrapping NavConfig projects.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    create_parser = subparsers.add_parser(
        "create",
        help="Create the default NavConfig environment structure.",
    )
    create_parser.add_argument(
        "--env",
        default="dev",
        help="Name of the environment to create (default: dev).",
    )
    create_parser.add_argument(
        "--path",
        default=".",
        help="Project directory where the structure should be created.",
    )

    return parser


def main(argv: list[str] | None = None) -> int:
    """Entry point for the kardex CLI."""
    parser = build_parser()
    args = parser.parse_args(argv)

    if args.command == "create":
        project_root = Path(args.path).resolve()
        created_paths = create_project_structure(args.env, project_root)
        LOGGER.info(
            "Created NavConfig project structure at %s (environment: %s)",
            project_root,
            args.env,
        )
        for name, path in created_paths.items():
            LOGGER.debug("%s -> %s", name, path)
        return 0

    parser.print_help()
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
