# -*- coding: utf-8 -*-
"""command line tool
Author  : CraftPilot
"""
import argparse
import os
import yaml
import shutil
from importlib_resources import files, as_file


# 支持的虚拟环境类型
SUPPORTED_ENV_TYPES = ['conda', 'venv', 'virtualenv', 'poetry', 'pipenv']


def entry():
    parser = argparse.ArgumentParser(prog='craftpilot')
    subparsers = parser.add_subparsers(
        title='These are common CraftPilot Dson commands used in various situations',
        metavar='command'
    )

    # init 命令
    init_parser = subparsers.add_parser(
        'init',
        help='Init a craftpilot python plugin environment'
    )
    init_parser.add_argument(
        'path',
        help='the path to plugin directory (optional, default is current directory)',
        nargs='?',
        default='.'
    )
    init_parser.add_argument('--name', help='the plugin name')
    init_parser.add_argument('--conda_env', help='conda env name (for conda environment)')
    init_parser.add_argument(
        '--env-type',
        choices=SUPPORTED_ENV_TYPES,
        help='virtual environment type: conda, venv, virtualenv, poetry, pipenv'
    )
    init_parser.add_argument(
        '--env-path',
        help='path to virtual environment (for venv/virtualenv, e.g., ./venv)'
    )
    init_parser.set_defaults(handle=handle_init)

    # run parser
    args = parser.parse_args()
    if hasattr(args, 'handle'):
        args.handle(args)
    else:
        parser.print_help()


def handle_init(args):
    """处理 init 命令"""
    try:
        plugin_path = os.path.abspath(args.path)
    except Exception as e:
        print('错误：路径无效')
        print(e)
        return

    # 确保目标目录存在
    if not os.path.exists(plugin_path):
        os.makedirs(plugin_path, exist_ok=True)
        print(f'创建目录: {plugin_path}')

    # 读取配置模板
    try:
        dson_text = files('craftpilot.pypapi').joinpath('pantry').joinpath('dson_config.yaml').read_text()
        dson_config = yaml.full_load(dson_text)
    except Exception as e:
        print(f'错误：无法读取配置模板 - {e}')
        return

    # 处理命令行参数
    # 插件名称
    if args.name:
        dson_config['name'] = args.name
    else:
        # 默认使用目录名作为插件名
        dson_config['name'] = os.path.basename(plugin_path)

    # 虚拟环境类型
    env_type = getattr(args, 'env_type', None)
    if env_type:
        dson_config['env_type'] = env_type
        # 移除不需要的字段
        if env_type != 'conda' and 'conda_env' in dson_config:
            del dson_config['conda_env']
    
    # Conda 环境名称
    if args.conda_env:
        dson_config['conda_env'] = args.conda_env
        if 'env_type' not in dson_config:
            dson_config['env_type'] = 'conda'
    
    # 虚拟环境路径
    env_path = getattr(args, 'env_path', None)
    if env_path:
        dson_config['env_path'] = env_path
        # 如果指定了路径但没指定类型，默认使用 venv
        if 'env_type' not in dson_config:
            dson_config['env_type'] = 'venv'

    # 清理配置中的注释内容（保留简洁的配置）
    clean_config = _clean_config_for_output(dson_config)
    
    # 写入配置文件
    config_path = os.path.join(plugin_path, 'dson_config.yaml')
    with open(config_path, 'w', encoding='utf-8') as f:
        yaml.safe_dump(clean_config, f, sort_keys=False, allow_unicode=True)
    print(f'创建配置文件: {config_path}')
    
    # 复制生成器脚本
    source = files('craftpilot.pypapi').joinpath('pantry').joinpath('dson_generator.py')
    generator_path = os.path.join(plugin_path, 'dson_generator.py')
    with as_file(source) as source_path:
        shutil.copyfile(source_path, generator_path)
    print(f'创建生成器脚本: {generator_path}')
    
    # 输出使用提示
    print('\n初始化完成！')
    print('\n下一步操作：')
    print('1. 编辑 dson_config.yaml 配置您的模块')
    print('2. 创建您的 Python 模块文件')
    print('3. 运行 python dson_generator.py 生成 DSON 文件')
    
    env_type = clean_config.get('env_type', 'conda')
    _print_env_setup_hint(env_type, clean_config)


def _clean_config_for_output(config: dict) -> dict:
    """
    清理配置字典，只保留有效字段
    """
    clean = {}
    
    # 必需字段
    clean['name'] = config.get('name', 'MyPlugin')
    clean['modules'] = config.get('modules', [])
    
    # 环境配置
    env_type = config.get('env_type')
    if env_type:
        clean['env_type'] = env_type
        
        if env_type == 'conda':
            clean['conda_env'] = config.get('conda_env', config.get('name', 'base'))
        elif env_type in ('venv', 'virtualenv'):
            clean['env_path'] = config.get('env_path', './venv')
        # poetry 和 pipenv 不需要额外配置
    else:
        # 默认 conda 配置（向后兼容）
        if 'conda_env' in config:
            clean['conda_env'] = config['conda_env']
    
    return clean


def _print_env_setup_hint(env_type: str, config: dict):
    """
    输出虚拟环境设置提示
    """
    print(f'\n虚拟环境设置提示 ({env_type}):')
    
    if env_type == 'conda':
        env_name = config.get('conda_env', 'base')
        print(f'  conda create -n {env_name} python=3.9')
        print(f'  conda activate {env_name}')
        print(f'  pip install craftpilot')
    
    elif env_type in ('venv', 'virtualenv'):
        env_path = config.get('env_path', './venv')
        print(f'  python -m venv {env_path}')
        if os.name != 'posix':
            print(f'  {env_path}\\Scripts\\activate')
        else:
            print(f'  source {env_path}/bin/activate')
        print(f'  pip install craftpilot')
    
    elif env_type == 'poetry':
        print('  poetry init')
        print('  poetry add craftpilot')
        print('  poetry install')
    
    elif env_type == 'pipenv':
        print('  pipenv install craftpilot')
        print('  pipenv shell')


if __name__ == '__main__':
    entry()