"""
CLI 入口点和命令行参数解析
"""

import sys
from pathlib import Path
from typing import Optional

import click

from create_goin import __version__
from create_goin.config import template_config
from create_goin.core import create_project
from create_goin.git_utils import GitCloneError
from create_goin.prompts import prompt_project_info


@click.command()
@click.argument("project_name", required=False)
@click.option(
    "--template",
    "-t",
    type=str,
    default=None,
    help="项目模板类型（可选值见 --list-templates）",
)
@click.option(
    "--output-dir",
    "-o",
    type=click.Path(),
    default=".",
    help="项目输出目录（默认为当前目录）",
)
@click.option(
    "--non-interactive",
    "-y",
    is_flag=True,
    help="非交互模式，使用默认值",
)
@click.option(
    "--list-templates",
    "-l",
    is_flag=True,
    help="列出所有可用的模板",
)
@click.version_option(version=__version__, prog_name="create-goin")
def main(
    project_name: Optional[str],
    template: Optional[str],
    output_dir: str,
    non_interactive: bool,
    list_templates: bool,
) -> None:
    """
    🚀 create-goin - Python 项目初始化工具

    快速创建标准化的 Python 项目骨架。

    示例：

    \b
    # 交互式创建项目
    $ create-goin

    \b
    # 直接指定项目名称
    $ create-goin my-awesome-project

    \b
    # 指定模板类型
    $ create-goin my-project -t ml-model-service

    \b
    # 列出所有可用模板
    $ create-goin --list-templates

    \b
    # 指定输出目录
    $ create-goin my-project -o /path/to/projects
    """
    try:
        # 列出模板
        if list_templates:
            click.echo(click.style("\n📚 可用的项目模板：\n", fg="green", bold=True))
            templates = template_config.get_all_templates()
            for name, cfg in templates.items():
                template_type = cfg.get("type", "unknown")
                type_icon = "📦" if template_type == "builtin" else "🔗"
                click.echo(f"{type_icon} {click.style(name, fg='cyan', bold=True)}")
                click.echo(f"   名称: {cfg.get('display_name', name)}")
                click.echo(f"   描述: {cfg.get('description', '无')}")
                click.echo(f"   类型: {template_type}")
                if template_type == "git":
                    click.echo(f"   仓库: {cfg.get('source', '无')}")
                click.echo()
            return

        click.echo(click.style("\n🚀 欢迎使用 create-goin！\n", fg="green", bold=True))

        # 如果是非交互模式且没有提供项目名，报错
        if non_interactive and not project_name:
            click.echo(
                click.style("❌ 非交互模式下必须提供项目名称", fg="red"),
                err=True,
            )
            sys.exit(1)

        # 选择模板
        if not template:
            template = template_config.get_default_template()
            # if not non_interactive:
            #     # 交互式选择模板
            #     template = prompt_template_selection()

        # 验证模板是否存在
        if not template_config.get_template(template):
            click.echo(
                click.style(f"❌ 模板不存在：{template}", fg="red"),
                err=True,
            )
            click.echo(
                click.style("\n💡 使用 --list-templates 查看可用模板", fg="yellow")
            )
            sys.exit(1)

        # 收集项目信息
        if non_interactive:
            project_info = {
                "name": project_name,
                "description": "",
                "author": "",
            }
        else:
            project_info = prompt_project_info(project_name)

        # 设置输出路径
        output_path = Path(output_dir).resolve()

        # 获取模板信息
        template_cfg = template_config.get_template(template)
        template_display_name = template_cfg.get("display_name", template)

        # 显示项目配置信息
        click.echo("\n" + "=" * 50)
        click.echo(click.style("📋 项目配置", fg="cyan", bold=True))
        click.echo("=" * 50)
        click.echo(f"项目名称: {click.style(project_info['name'], fg='yellow')}")
        click.echo(f"项目描述: {project_info['description'] or '(无)'}")
        click.echo(f"作者名称: {project_info['author'] or '(无)'}")
        click.echo(f"模板类型: {template_display_name} ({template})")
        click.echo(f"输出目录: {output_path}")
        click.echo("=" * 50 + "\n")

        # 确认创建
        if not non_interactive:
            if not click.confirm(click.style("✨ 确认创建项目？", fg="green"), default=True):
                click.echo(click.style("\n❌ 已取消创建", fg="yellow"))
                sys.exit(0)

        # 创建项目
        click.echo(click.style("\n🔨 正在创建项目...\n", fg="blue"))
        project_path = create_project(
            project_name=project_info["name"],
            template_name=template,
            output_dir=output_path,
            project_info=project_info,
        )

        # 成功提示
        click.echo(click.style("\n" + "=" * 50, fg="green"))
        click.echo(click.style("✅ 项目创建成功！", fg="green", bold=True))
        click.echo(click.style("=" * 50 + "\n", fg="green"))

        # 后续步骤提示
        click.echo(click.style("📝 下一步操作：\n", fg="cyan", bold=True))
        click.echo("  1. 进入项目目录：")
        click.echo(f"     {click.style(f'cd {project_path.name}', fg='yellow')}")
        click.echo("\n  2. 创建虚拟环境（可选）：")
        click.echo(f"     {click.style('python -m venv .venv', fg='yellow')}")
        click.echo(f"     {click.style('source .venv/bin/activate', fg='yellow')}  # Linux/Mac")
        windows_activate = '.venv\\Scripts\\activate'
        click.echo(f"     {click.style(windows_activate, fg='yellow')}     # Windows")
        click.echo("\n  3. 安装开发依赖：")
        pip_install_cmd = 'pip install -e ".[dev]"'
        click.echo(f"     {click.style(pip_install_cmd, fg='yellow')}")
        click.echo("\n  4. 开始开发！")
        click.echo(f"     {click.style('Happy coding! 🎉', fg='magenta')}\n")

    except KeyboardInterrupt:
        click.echo(click.style("\n\n❌ 操作已取消", fg="yellow"))
        sys.exit(130)
    except GitCloneError as e:
        click.echo(click.style(f"\n❌ Git 克隆失败：{e}", fg="red"), err=True)
        click.echo(click.style("\n💡 请检查：", fg="yellow"))
        click.echo("   1. Git 是否已安装")
        click.echo("   2. 仓库地址是否正确")
        click.echo("   3. 网络连接是否正常")
        click.echo("   4. 是否有访问权限")
        sys.exit(1)
    except Exception as e:
        click.echo(click.style(f"\n❌ 错误：{e}", fg="red"), err=True)
        sys.exit(1)


def prompt_template_selection() -> str:
    """
    交互式选择模板

    Returns:
        选择的模板名称
    """
    templates = template_config.get_all_templates()
    template_names = list(templates.keys())

    if not template_names:
        return template_config.get_default_template()

    # 显示模板列表
    click.echo(click.style("📚 可用模板：\n", fg="cyan"))
    for idx, name in enumerate(template_names, 1):
        cfg = templates[name]
        type_icon = "📦" if cfg.get("type") == "builtin" else "🔗"
        click.echo(f"{idx}. {type_icon} {click.style(name, fg='yellow')} - {cfg.get('description', '')}")

    # 选择模板
    while True:
        choice = click.prompt(
            click.style("\n选择模板", fg="cyan"),
            type=str,
            default="1",
        )

        # 支持数字或名称
        if choice.isdigit():
            idx = int(choice) - 1
            if 0 <= idx < len(template_names):
                return template_names[idx]
        elif choice in template_names:
            return choice

        click.echo(click.style("❌ 无效的选择，请重新输入", fg="red"))


if __name__ == "__main__":
    main()
