import typer
import logging
from pathlib import Path

from utils import utils
from config import TEMPLATES, TEMPLATES_DIR

logger = logging.getLogger(__name__)


def init():
    """
    CLI entrypoint for project scaffolding using Cookiecutter.
    """
    try:
        logger.info("Starting project scaffolding (Cookiecutter mode)")

        #INPUT COLLECTION
        inputs = utils.collect_inputs()

        #STORAGE RESOLUTION
        storage = utils.resolve_storage(inputs["storage_type"])

        #TEMPLATE RESOLUTION
        template_dir = str(
            TEMPLATES_DIR / TEMPLATES[inputs["template"]]["dir"]
        )

        #SLUG GENERATION
        project_slug = utils.generate_slug(inputs["project_name"])

        #COOKIECUTTER GENERATION
        logger.info("Running Cookiecutter")

        utils.generate_project(
            template_dir=template_dir,
            output_dir=inputs["output_dir"],
            context={
                "project_name": inputs["project_name"],
                "project_slug": project_slug,
                "version": inputs["version"],
                "author": inputs["author"],
                "storage": storage,
                "workspace": inputs["workspace"],
            },
        )

        #FINAL PATH
        project_path = Path(inputs["output_dir"]) / project_slug

        #OUTPUT SUMMARY
        utils.print_summary(
            project_path,
            storage,
            inputs["project_name"],
            inputs["version"],
        )

        logger.info("Project scaffolding completed successfully")

    except Exception as e:
        logger.exception("Project creation failed")
        typer.echo(f"Error: {e}")
        raise typer.Exit(code=1)