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()

        # TEMPLATE RESOLUTION — always use template base for cookiecutter, yml_dir for structure/functions
        cookiecutter_dir = TEMPLATES[inputs["template"]].get("cookiecutter_dir", TEMPLATES[inputs["template"]]["dir"])
        template_dir = str(TEMPLATES_DIR / cookiecutter_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"],
            },
        )
        project_type = inputs.get("etl_type") or inputs.get("ml_type")
        if project_type:
            utils.generate_project_from_yml(
                template=inputs["template"],
                etl_type=project_type,
                output_dir=inputs["output_dir"],
                project_slug=project_slug,
            )
        project_path = Path(inputs["output_dir"]).expanduser().resolve() / project_slug

        utils.write_last_scaffolded_project(project_path)

        #OUTPUT SUMMARY
        utils.print_summary(
            project_path,
            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)