import typer
import logging
from pathlib import Path

from acc_cli.utils import utils
from acc_cli.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"])

        if not Path(template_dir).exists():
            typer.echo(
                f"Template '{inputs['template']}' is not yet available.",
                err=True
            )
            raise typer.Exit(code=1)

        # 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 typer.Exit:
        raise
    except Exception as e:
        logger.exception("Project creation failed")
        typer.echo(f"Error: {e}")
        raise typer.Exit(code=1)

