"""
核心项目创建逻辑
"""

import importlib
import shutil
import tempfile
from pathlib import Path
from typing import Dict

import click

from create_goin.config import template_config
from create_goin.git_utils import (
    GitCloneError,
    clone_repository,
    remove_git_directory,
    rename_project_directories,
    replace_variables_in_directory,
)
from create_goin.utils import create_directory, normalize_name, validate_project_name, write_file


def create_project_from_builtin(
    project_name: str,
    template_name: str,
    project_path: Path,
    project_info: Dict[str, str],
) -> None:
    """
    从内置模板创建项目

    Args:
        project_name: 项目名称
        template_name: 模板名称
        project_path: 项目路径
        project_info: 项目信息字典

    Raises:
        ModuleNotFoundError: 模板不存在
    """
    # 加载模板
    try:
        template_module = importlib.import_module(
            f"create_goin.templates.{template_name}.template_files"
        )
    except ModuleNotFoundError:
        raise ModuleNotFoundError(f"内置模板不存在：{template_name}")

    # 准备模板变量
    template_vars = {
        "project_name": project_name,
        "project_name_normalized": normalize_name(project_name),
        "description": project_info.get("description", ""),
        "author": project_info.get("author", ""),
    }

    # 获取模板文件
    files = template_module.get_template_files(template_vars)

    # 创建项目目录
    create_directory(project_path)

    # 写入文件
    for file_path, content in files.items():
        full_path = project_path / file_path
        write_file(full_path, content)


def create_project_from_git(
    project_name: str,
    template_config_dict: Dict,
    project_path: Path,
    project_info: Dict[str, str],
) -> None:
    """
    从 Git 仓库创建项目

    Args:
        project_name: 项目名称
        template_config_dict: 模板配置字典
        project_path: 项目路径
        project_info: 项目信息字典

    Raises:
        GitCloneError: Git 克隆失败
    """
    repo_url = template_config_dict.get("source")
    branch = template_config_dict.get("branch", "main")

    # 获取 Git 配置
    git_config = template_config.get_git_config()
    depth = git_config.get("depth", 1)
    timeout = git_config.get("timeout", 60)

    click.echo(f"   📥 正在从 Git 仓库克隆模板...")
    click.echo(f"   仓库地址: {click.style(repo_url, fg='cyan')}")
    click.echo(f"   分支: {click.style(branch, fg='cyan')}")

    # 创建临时目录
    with tempfile.TemporaryDirectory() as tmpdir:
        temp_path = Path(tmpdir) / "template"

        try:
            # 克隆仓库
            clone_repository(
                repo_url=repo_url,
                target_dir=temp_path,
                branch=branch,
                depth=depth,
                timeout=timeout,
            )

            click.echo(f"   ✅ 克隆成功")

            # 删除 .git 目录
            remove_git_directory(temp_path)

            # 准备变量替换
            package_name = normalize_name(project_name)
            variables = {
                "PROJECT_NAME": project_name,
                "PROJECT_NAME_NORMALIZED": package_name,
                "PROJECT_DESCRIPTION": project_info.get("description", ""),
                "AUTHOR_NAME": project_info.get("author", ""),
            }

            click.echo(f"   🔄 正在替换模板变量...")

            # 替换文件中的变量
            replace_variables_in_directory(temp_path, variables)

            # 重命名目录（如果存在模板项目名）
            # 常见的模板项目名占位符
            template_placeholders = [
                "template",
                "project_name",
                "PROJECT_NAME",
                "{{PROJECT_NAME}}",
            ]
            for placeholder in template_placeholders:
                rename_project_directories(temp_path, placeholder, package_name)

            click.echo(f"   ✅ 变量替换完成")

            # 复制到目标目录
            shutil.copytree(temp_path, project_path)

        except GitCloneError as e:
            raise GitCloneError(f"从 Git 仓库创建项目失败: {e}")


def create_project(
    project_name: str,
    template_name: str,
    output_dir: Path,
    project_info: Dict[str, str],
) -> Path:
    """
    创建项目

    Args:
        project_name: 项目名称
        template_name: 模板名称
        output_dir: 输出目录
        project_info: 项目信息字典

    Returns:
        创建的项目路径

    Raises:
        ValueError: 项目名称无效或模板不存在
        FileExistsError: 项目目录已存在
        GitCloneError: Git 克隆失败
    """
    # 验证项目名称
    is_valid, error_msg = validate_project_name(project_name)
    if not is_valid:
        raise ValueError(error_msg)

    # 项目路径
    project_path = output_dir / project_name
    if project_path.exists():
        raise FileExistsError(f"目录已存在：{project_path}")

    # 获取模板配置
    template_cfg = template_config.get_template(template_name)
    if not template_cfg:
        raise ValueError(f"模板不存在：{template_name}")

    # 根据模板类型创建项目
    if template_config.is_builtin_template(template_name):
        # 内置模板
        create_project_from_builtin(project_name, template_name, project_path, project_info)
    elif template_config.is_git_template(template_name):
        # Git 模板
        create_project_from_git(project_name, template_cfg, project_path, project_info)
    else:
        raise ValueError(f"未知的模板类型：{template_cfg.get('type')}")

    return project_path
