"""paracord init command - Create a new Paracord project."""

from pathlib import Path
from typing import Annotated, Optional

import typer

from paracord.core.copier import run_copier_copy, PARACORD_TEMPLATE
from paracord.core.github import register_project_sync
from paracord.utils.console import (
    console,
    print_header,
    print_success,
    print_error,
    print_info,
    print_next_steps,
)


def init(
    project_name: Annotated[
        Optional[str],
        typer.Argument(
            help="Name of the project to create. Creates a new directory with this name.",
        ),
    ] = None,
    template: Annotated[
        str,
        typer.Option(
            "--template", "-t",
            help="Template to use for the project.",
        ),
    ] = PARACORD_TEMPLATE,
) -> None:
    """Create a new Paracord project from the template.

    This command runs copier to create a new project from the
    paracord-run/dash template. You'll be prompted for project
    configuration options interactively.
    """
    print_header("Paracord Init", "Creating a new Paracord project")

    # Determine destination
    if project_name:
        destination = Path.cwd() / project_name
        if destination.exists():
            print_error(f"Directory '{project_name}' already exists.")
            raise typer.Exit(1)
        print_info(f"Creating project in: [path]{destination}[/path]")
    else:
        destination = None
        print_info("Creating project in current directory")

    # Run copier
    console.print()
    success = run_copier_copy(
        template=template,
        project_name=project_name,
    )

    if not success:
        print_error("Failed to create project.")
        raise typer.Exit(1)

    # Attempt community registration (non-blocking)
    console.print()
    print_info("Registering with Paracord community...")
    register_project_sync(project_name)

    # Success message
    console.print()
    print_success("Project created successfully!")

    # Next steps
    steps = []
    if project_name:
        steps.append(f"cd {project_name}")
    steps.extend([
        "uv sync",
        "paracord run  # to see available tasks",
    ])
    print_next_steps(steps)
