"""
CLI interface for PyUploader
"""
import os
import subprocess
import sys
import json
import click
from pathlib import Path
import tomli
import tomli_w

# 导入语言包
from .lang import load_translations, get_supported_languages

# 创建自定义的中文帮助格式化器类
class ChineseHelpFormatter(click.HelpFormatter):
    def write_usage(self, prog, args='', prefix='Usage: '):
        # 汉化Usage标题
        super().write_usage(prog, args, prefix='用法: ')
    
    def write_heading(self, heading):
        # 替换英文标题为中文
        if heading == 'Options':
            heading = '选项'
        elif heading == 'Commands':
            heading = '命令'
        super().write_heading(heading)

# 创建自定义的Group类，根据语言设置选择帮助格式化器
class CustomLanguageGroup(click.Group):
    def make_context(self, info_name, args, parent=None, **extra):
        # 解析参数以获取语言设置
        ctx = super().make_context(info_name, args, parent, **extra)
        lang = ctx.params.get('lang', None)
        
        # 如果是根命令且没有语言设置，使用默认语言
        if parent is None and lang is None:
            config = load_config()
            lang = config.get('language', 'zh')
        
        # 如果语言是中文，使用中文帮助格式化器
        if lang == 'zh':
            self.help_formatter_class = ChineseHelpFormatter
        else:
            # 否则使用默认的帮助格式化器
            self.help_formatter_class = click.HelpFormatter
        
        return ctx

# 获取配置文件路径
def get_config_path():
    """获取配置文件的路径，保存在当前目录"""
    return Path.cwd() / 'config.json'

# 加载配置
def load_config():
    """从配置文件加载设置"""
    config_path = get_config_path()
    if not config_path.exists():
        return {}
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception:
        return {}

# 保存配置
def save_config(config):
    """保存配置到文件"""
    config_path = get_config_path()
    config_path.parent.mkdir(parents=True, exist_ok=True)
    
    with open(config_path, 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=4, ensure_ascii=False)
    
    # 设置文件权限为600（仅拥有者可读写）
    try:
        os.chmod(config_path, 0o600)
    except Exception:
        pass  # 在Windows上可能会失败

# 获取翻译文本
def _(text_key, *args, lang='zh'):
    """获取翻译后的文本"""
    # 加载指定语言的翻译
    lang_translations = load_translations(lang)
    
    # 尝试从指定语言中获取翻译
    if text_key in lang_translations:
        if args:
            return lang_translations[text_key].format(*args)
        return lang_translations[text_key]
    
    # 如果没有找到翻译，尝试从英文版本获取
    if lang != 'en':
        en_translations = load_translations('en')
        if text_key in en_translations:
            if args:
                return en_translations[text_key].format(*args)
            return en_translations[text_key]
    
    # 如果都没有找到，返回原始键
    return text_key

# 主命令组
@click.group(cls=CustomLanguageGroup)
@click.option('--lang', default=None, type=click.Choice(['en', 'zh']), help='设置语言（en/zh）')
@click.pass_context
def cli(ctx, lang):
    """PyPI上传工具 - 一个自动化上传Python包到PyPI的命令行工具"""
    ctx.ensure_object(dict)
    
    # 加载配置
    config = load_config()
    ctx.obj['config'] = config
    
    # 设置语言
    if lang:
        ctx.obj['lang'] = lang
    else:
        ctx.obj['lang'] = config.get('language', 'zh')

@cli.command()
@click.option('--package-dir', '-d', default='.', help='包目录', type=click.Path(exists=True))
@click.pass_context
def init(ctx, package_dir):
    """初始化PyPI Uploader配置和包元数据"""
    config = ctx.obj['config']
    lang = ctx.obj['lang']
    
    click.echo(_('init_intro', lang=lang))
    
    # 获取用户输入
    default_repo = config.get('repository', 'pypi')
    repository = click.prompt(_('enter_repository', lang=lang), default=default_repo)
    
    default_username = config.get('username', '__token__')
    username = click.prompt(_('enter_username', lang=lang), default=default_username)
    
    password = click.prompt(_('enter_api_key', lang=lang), hide_input=True, confirmation_prompt=True)
    
    # 保存配置
    config['repository'] = repository
    config['username'] = username
    config['password'] = password
    config['language'] = lang
    
    save_config(config)
    
    config_path = get_config_path()
    click.echo(_('config_file_created', str(config_path), lang=lang))
    click.echo(_('config_file_permissions', str(config_path), lang=lang))
    click.echo(_('config_saved', lang=lang))
    
    # 处理pyproject.toml
    package_path = Path(package_dir).absolute()
    pyproject_path = package_path / 'pyproject.toml'
    
    click.echo(_('init_pyproject', str(pyproject_path), lang=lang))
    
    # 检查是否存在pyproject.toml文件
    data = {}
    if pyproject_path.exists():
        try:
            with open(pyproject_path, 'rb') as f:
                data = tomli.load(f)
        except Exception as e:
            click.echo(click.style(_('load_pyproject_failed', str(e), lang=lang), fg='red'))
    
    # 获取项目信息
    project = data.get('project', {})
    
    # 提示用户输入项目信息
    project['name'] = click.prompt(_('enter_name', lang=lang), default=project.get('name', ''))
    project['description'] = click.prompt(_('enter_description', lang=lang), default=project.get('description', ''))
    
    # 处理作者信息
    authors = project.get('authors', [{}])[0] if project.get('authors') else {}
    author_name = click.prompt(_('enter_author', lang=lang), default=authors.get('name', ''))
    author_email = click.prompt(_('enter_author_email', lang=lang), default=authors.get('email', ''))
    project['authors'] = [{'name': author_name, 'email': author_email}]
    
    # 设置版本
    project['version'] = click.prompt(_('enter_version', lang=lang), default=project.get('version', '0.1.0'))
    
    # Python版本要求
    project['requires-python'] = click.prompt(
        _('enter_python_requires', lang=lang), 
        default=project.get('requires-python', '>=3.7')
    )
    
    # 新增配置项：依赖
    dependencies_input = click.prompt(_('enter_dependencies', lang=lang), default='', show_default=False)
    if dependencies_input:
        project['dependencies'] = [dep.strip() for dep in dependencies_input.split(',') if dep.strip()]
    
    # 新增配置项：许可证
    license_value = click.prompt(_('enter_license', lang=lang), default='MIT')
    project['license'] = {'file': 'LICENSE'}
    
    # 新增配置项：关键词
    keywords_input = click.prompt(_('enter_keywords', lang=lang), default='', show_default=False)
    if keywords_input:
        project['keywords'] = [kw.strip() for kw in keywords_input.split(',') if kw.strip()]
    
    # 新增配置项：项目URLs
    project_url = click.prompt(_('enter_project_url', lang=lang), default='', show_default=False)
    bugtracker_url = click.prompt(_('enter_bugtracker_url', lang=lang), default='', show_default=False)
    repository_url = click.prompt(_('enter_repository_url', lang=lang), default='', show_default=False)
    
    project_urls = {}
    if project_url:
        project_urls['Homepage'] = project_url
    if bugtracker_url:
        project_urls['Bug Tracker'] = bugtracker_url
    if repository_url:
        project_urls['Repository'] = repository_url
    
    if project_urls:
        project['project_urls'] = project_urls
    
    # 确保有classifiers
    if not project.get('classifiers'):
        project['classifiers'] = [
            'Programming Language :: Python :: 3',
            f'License :: OSI Approved :: {license_value} License',
            'Operating System :: OS Independent',
        ]
    
    # 保存更新后的信息
    data['project'] = project
    
    # 如果是新项目，添加必要的配置
    if not data.get('build-system'):
        data['build-system'] = {
            'requires': ['setuptools>=61.0'],
            'build-backend': 'setuptools.build_meta'
        }
    
    # 保存pyproject.toml
    with open(pyproject_path, 'wb') as f:
        tomli_w.dump(data, f)
    
    click.echo(_('pyproject_saved', str(pyproject_path), lang=lang))

@cli.command()
@click.option('--package-dir', '-d', default='.', help='要编辑的包目录', type=click.Path(exists=True))
@click.pass_context
def edit(ctx, package_dir):
    """编辑包的元数据信息"""
    lang = ctx.obj['lang']
    click.echo(_('edit_intro', lang=lang))
    
    package_path = Path(package_dir).absolute()
    pyproject_path = package_path / 'pyproject.toml'
    
    if not pyproject_path.exists():
        click.echo(click.style(_('no_package', lang=lang), fg='red'))
        sys.exit(1)
    
    try:
        # 读取现有的pyproject.toml文件
        with open(pyproject_path, 'rb') as f:
            data = tomli.load(f)
        
        # 获取项目信息
        project = data.get('project', {})
        
        # 提示用户输入新的信息
        project['name'] = click.prompt(_('enter_name', lang=lang), default=project.get('name', ''))
        project['description'] = click.prompt(_('enter_description', lang=lang), default=project.get('description', ''))
        
        # 处理作者信息
        authors = project.get('authors', [{}])[0]
        author_name = click.prompt(_('enter_author', lang=lang), default=authors.get('name', ''))
        author_email = click.prompt(_('enter_author_email', lang=lang), default=authors.get('email', ''))
        project['authors'] = [{'name': author_name, 'email': author_email}]
        
        # 获取当前版本
        current_version = project.get('version', '0.1.0')
        click.echo(_('current_version', current_version, lang=lang))
        new_version = click.prompt(_('enter_new_version', lang=lang), default=current_version)
        if new_version:
            project['version'] = new_version
        
        # Python版本要求
        project['requires-python'] = click.prompt(
            _('enter_python_requires', lang=lang), 
            default=project.get('requires-python', '>=3.7')
        )
        
        # 新增配置项：依赖
        current_dependencies = ', '.join(project.get('dependencies', []))
        dependencies_input = click.prompt(
            _('enter_dependencies', lang=lang), 
            default=current_dependencies, 
            show_default=True
        )
        if dependencies_input:
            project['dependencies'] = [dep.strip() for dep in dependencies_input.split(',') if dep.strip()]
        elif 'dependencies' in project:
            del project['dependencies']
        
        # 新增配置项：许可证
        current_license = 'MIT'
        if 'license' in project:
            license_file = project['license'].get('file', 'LICENSE')
            if 'MIT' in license_file.upper():
                current_license = 'MIT'
            elif 'APACHE' in license_file.upper():
                current_license = 'Apache'
            elif 'GPL' in license_file.upper():
                current_license = 'GPL'
        
        license_value = click.prompt(_('enter_license', lang=lang), default=current_license)
        project['license'] = {'file': 'LICENSE'}
        
        # 更新classifiers中的许可证
        if 'classifiers' in project:
            for i, classifier in enumerate(project['classifiers']):
                if classifier.startswith('License :: OSI Approved ::'):
                    project['classifiers'][i] = f'License :: OSI Approved :: {license_value} License'
                    break
        
        # 新增配置项：关键词
        current_keywords = ', '.join(project.get('keywords', []))
        keywords_input = click.prompt(
            _('enter_keywords', lang=lang), 
            default=current_keywords, 
            show_default=True
        )
        if keywords_input:
            project['keywords'] = [kw.strip() for kw in keywords_input.split(',') if kw.strip()]
        elif 'keywords' in project:
            del project['keywords']
        
        # 新增配置项：项目URLs
        project_urls = project.get('project_urls', {})
        project_url = click.prompt(
            _('enter_project_url', lang=lang), 
            default=project_urls.get('Homepage', ''), 
            show_default=True
        )
        bugtracker_url = click.prompt(
            _('enter_bugtracker_url', lang=lang), 
            default=project_urls.get('Bug Tracker', ''), 
            show_default=True
        )
        repository_url = click.prompt(
            _('enter_repository_url', lang=lang), 
            default=project_urls.get('Repository', ''), 
            show_default=True
        )
        
        # 更新或创建项目URLs
        new_project_urls = {}
        if project_url:
            new_project_urls['Homepage'] = project_url
        if bugtracker_url:
            new_project_urls['Bug Tracker'] = bugtracker_url
        if repository_url:
            new_project_urls['Repository'] = repository_url
        
        if new_project_urls:
            project['project_urls'] = new_project_urls
        elif 'project_urls' in project:
            del project['project_urls']
        
        # 保存更新后的信息
        data['project'] = project
        with open(pyproject_path, 'wb') as f:
            tomli_w.dump(data, f)
        
        if new_version and new_version != current_version:
            click.echo(_('version_updated', new_version, lang=lang))
        
        click.echo(_('edit_success', lang=lang))
        
    except Exception as e:
        click.echo(click.style(_('edit_failed', str(e), lang=lang), fg='red'))
        sys.exit(1)

@cli.command()
@click.option('-d', '--package-dir', type=click.Path(exists=True, file_okay=False), default='.', help=_('package_dir_help', lang='zh'))
@click.pass_context
def fix(ctx, package_dir):
    """修复pyproject.toml文件的格式错误"""
    
    # 获取语言配置
    lang = ctx.obj['lang']
    click.echo(_('fix_intro', lang=lang))
    
    # 使用Path对象处理文件路径
    pyproject_path = Path(package_dir) / 'pyproject.toml'
    
    # 检查pyproject.toml是否存在
    if not pyproject_path.exists():
        click.echo(click.style(_('no_package', lang=lang), fg='red'))
        sys.exit(1)
    
    try:
        # 导入必要的模块
        import re
        import os
        
        # 读取文件内容
        raw_content = pyproject_path.read_text(encoding='utf-8')
        
        # 初始化是否有需要修复的标志
        needs_fix = False
        
        # 检查并修复常见问题，无论文件是否可以被解析
        # 1. 修复description拼写错误
        if 'cription = ' in raw_content:
            raw_content = raw_content.replace('cription = ', 'description = ')
            needs_fix = True
        
        # 2. 修复URL前缀错误（如tps:// 改为 https://）
        if 'tps://' in raw_content:
            # 只替换'tps://'，确保不影响其他内容
            raw_content = raw_content.replace('tps://', 'https://')
            needs_fix = True
        
        # 如果有需要修复的内容，尝试解析和保存
        if needs_fix:
            # 保存修复后的内容到临时文件
            temp_path = pyproject_path.with_suffix('.toml.temp')
            temp_path.write_text(raw_content, encoding='utf-8')
            
            try:
                # 尝试解析修复后的文件
                with open(temp_path, 'rb') as f:
                    parsed_data = tomli.load(f)
                
                # 如果解析成功，保存修复后的文件
                pyproject_path.write_text(raw_content, encoding='utf-8')
                
                # 删除临时文件
                if temp_path.exists():
                    temp_path.unlink()
                
                click.echo(click.style(_('fix_success', lang=lang), fg='green'))
                click.echo(_('pyproject_fixed', str(pyproject_path), lang=lang))
            except Exception as parse_error:
                click.echo(click.style(_('fix_parse_failed', str(parse_error), lang=lang), fg='red'))
                click.echo(_('fix_manual_help', lang=lang))
                if 'temp_path' in locals() and temp_path.exists():
                    temp_path.unlink()
                sys.exit(1)
        else:
            # 即使文件可以被解析，也要尝试解析以确认格式是否有效
            try:
                with open(pyproject_path, 'rb') as f:
                    data = tomli.load(f)
                click.echo(click.style("pyproject.toml文件格式已经正确，无需修复。", fg='green'))
            except Exception as e:
                click.echo(click.style(_('fix_parse_failed', str(e), lang=lang), fg='red'))
                click.echo(_('fix_manual_help', lang=lang))
                sys.exit(1)
    except Exception as e:
        click.echo(click.style(_('fix_failed', str(e), lang=lang), fg='red'))
        sys.exit(1)

@cli.command()
@click.option('--package-dir', '-d', default='.', help='要上传的包目录', type=click.Path(exists=True))
@click.option('--repository', '-r', default=None, help='要上传的PyPI仓库（pypi或testpypi）')
@click.option('--username', '-u', default=None, help='PyPI认证的用户名')
@click.option('--password', '-p', default=None, help='PyPI认证的密码或API令牌')
@click.option('--dist-dir', default='dist', help='包含分发文件的目录')
@click.option('--build/--no-build', default=True, help='是否在上传前构建包')
@click.option('--clean/--no-clean', default=True, help='是否在构建前清理构建目录')
@click.option('--skip-existing', is_flag=True, help='如果分发版本已存在则跳过上传')
@click.option('--interactive', '-i', is_flag=True, help='以交互模式运行')
@click.pass_context
def upload(ctx, package_dir, repository, username, password, dist_dir, build, clean, skip_existing, interactive):
    """上传包到PyPI"""
    config = ctx.obj['config']
    lang = ctx.obj['lang']
    
    # 如果没有提供参数且有配置，使用配置值
    if not repository and 'repository' in config:
        repository = config['repository']
    if not username and 'username' in config:
        username = config['username']
    if not password and 'password' in config:
        password = config['password']
    
    # 设置默认值
    if not repository:
        repository = 'pypi'
    if not username:
        username = '__token__'
    
    package_path = Path(package_dir).absolute()
    dist_path = package_path / dist_dir
    
    # 在交互式模式下，询问用户确认
    if interactive:
        # 询问包目录
        user_dir = click.prompt(_('enter_package_dir', lang=lang), default=str(package_dir))
        if user_dir != package_dir:
            package_path = Path(user_dir).absolute()
            dist_path = package_path / dist_dir
        
        # 询问仓库
        user_repo = click.prompt(_('enter_repository', lang=lang), default=repository)
        if user_repo:
            repository = user_repo
        
        # 如果配置中没有密码或交互式模式，询问密码
        if not password:
            password = click.prompt(_('enter_api_key', lang=lang), hide_input=True)
        
        # 检查是否是有效的Python包
        if not (package_path / 'setup.py').exists() and not (package_path / 'pyproject.toml').exists():
            click.echo(click.style(_('no_package', lang=lang), fg='red'))
            sys.exit(1)
        
        # 询问版本
        if build:
            current_version = '0.1.0'
            pyproject_path = package_path / 'pyproject.toml'
            if pyproject_path.exists():
                try:
                    with open(pyproject_path, 'rb') as f:
                        data = tomli.load(f)
                        current_version = data.get('project', {}).get('version', '0.1.0')
                except Exception:
                    pass
            
            click.echo(_('current_version', current_version, lang=lang))
            new_version = click.prompt(_('enter_new_version', lang=lang), default='')
            
            # 如果用户提供了新版本，更新pyproject.toml
            if new_version and new_version != current_version:
                if pyproject_path.exists():
                    try:
                        with open(pyproject_path, 'rb') as f:
                            data = tomli.load(f)
                        data.setdefault('project', {})['version'] = new_version
                        with open(pyproject_path, 'wb') as f:
                            tomli_w.dump(data, f)
                        click.echo(_('version_updated', new_version, lang=lang))
                    except Exception as e:
                        click.echo(click.style(_('edit_failed', str(e), lang=lang), fg='yellow'))
        
        # 确认上传
        if not click.confirm(_('confirm_upload', lang=lang), default=True):
            click.echo(_('upload_cancelled', lang=lang))
            sys.exit(0)
    else:
        # 非交互式模式，检查是否是有效的Python包
        if not (package_path / 'setup.py').exists() and not (package_path / 'pyproject.toml').exists():
            click.echo(click.style(_('no_package', lang=lang), fg='red'))
            sys.exit(1)
    
    # 清理构建目录
    if clean and build:
        clean_build_dirs(package_path, lang)
    
    # 构建包
    if build:
        if not build_package(package_path, lang):
            click.echo(click.style(_('build_failed', lang=lang), fg='red'))
            sys.exit(1)
    
    # 检查分发目录
    if not dist_path.exists():
        click.echo(click.style(_('dist_not_exist', str(dist_path), lang=lang), fg='red'))
        sys.exit(1)
    
    # 上传包
    if not upload_package(dist_path, repository, username, password, skip_existing, lang):
        click.echo(click.style(_('upload_failed', lang=lang), fg='red'))
        sys.exit(1)
    
    click.echo(click.style(_('upload_success', lang=lang), fg='green'))

# 设置别名，保持向后兼容
main = upload


def clean_build_dirs(package_path, lang='zh'):
    """清理构建目录"""
    directories_to_clean = ['build', 'dist', '*.egg-info']
    
    for pattern in directories_to_clean:
        for path in package_path.glob(pattern):
            if path.is_dir():
                click.echo(_('cleaning_dir', str(path), lang=lang))
                import shutil
                try:
                    shutil.rmtree(path)
                except Exception as e:
                    click.echo(click.style(_('clean_failed', str(path), str(e), lang=lang), fg='yellow'))


def build_package(package_path, lang='zh'):
    """构建Python包"""
    click.echo(_('building', lang=lang))
    try:
        # 使用subprocess运行构建命令
        result = subprocess.run(
            [sys.executable, '-m', 'build', '--sdist', '--wheel', str(package_path)],
            capture_output=True,
            text=True,
            check=False
        )
        
        if result.returncode != 0:
            click.echo(click.style(_('building_output', result.stdout, lang=lang), fg='yellow'))
            click.echo(click.style(_('building_error', result.stderr, lang=lang), fg='red'))
            return False
        
        click.echo(_('build_success', lang=lang))
        return True
    except Exception as e:
        click.echo(click.style(_('building_error', str(e), lang=lang), fg='red'))
        return False


def upload_package(dist_path, repository, username, password, skip_existing, lang='zh'):
    """上传包到PyPI"""
    click.echo(_('uploading_to', repository, lang=lang))
    
    # 构建twine命令
    twine_cmd = ['twine', 'upload', '--repository', repository]
    
    # 添加认证信息（如果提供）
    if username:
        twine_cmd.extend(['--username', username])
    if password:
        twine_cmd.extend(['--password', password])
    
    # 如果请求，添加跳过现有标志
    if skip_existing:
        twine_cmd.append('--skip-existing')
    
    # 添加分发文件
    twine_cmd.append(str(dist_path / '*'))
    
    try:
        # 使用subprocess运行twine上传
        result = subprocess.run(
            twine_cmd,
            capture_output=True,
            text=True,
            check=False
        )
        
        if result.returncode != 0:
            click.echo(click.style(_('twine_output', result.stdout, lang=lang), fg='yellow'))
            click.echo(click.style(_('twine_error', result.stderr, lang=lang), fg='red'))
            return False
        
        click.echo(_('upload_success_repo', repository, lang=lang))
        return True
    except Exception as e:
        click.echo(click.style(_('twine_error', str(e), lang=lang), fg='red'))
        return False


@cli.command()
@click.option('--force', '-f', is_flag=True, help='强制覆盖已有的.pypirc文件')
@click.pass_context
def pypirc_config(ctx, force):
    """自动配置~/.pypirc文件"""
    lang = ctx.obj['lang']
    click.echo(_('pypirc_config_intro', lang=lang))
    
    # 获取主目录
    home_dir = Path.home()
    pypirc_path = home_dir / '.pypirc'
    
    # 检查文件是否存在
    if pypirc_path.exists() and not force:
        overwrite = click.confirm(_('pypirc_exists', str(pypirc_path), lang=lang), default=False)
        if not overwrite:
            click.echo(_('pypirc_config_canceled', lang=lang))
            return
    
    # 获取用户输入
    click.echo(_('pypirc_config_instruction', lang=lang))
    
    # PyPI配置
    click.echo('\n--- PyPI 配置 ---')
    pypi_username = click.prompt(_('enter_pypi_username', lang=lang), default='__token__')
    pypi_password = click.prompt(_('enter_pypi_password', lang=lang), hide_input=True, confirmation_prompt=True)
    
    # TestPyPI配置
    click.echo('\n--- TestPyPI 配置 ---')
    include_testpypi = click.confirm(_('include_testpypi', lang=lang), default=True)
    testpypi_username = ''
    testpypi_password = ''
    if include_testpypi:
        testpypi_username = click.prompt(_('enter_testpypi_username', lang=lang), default='__token__')
        testpypi_password = click.prompt(_('enter_testpypi_password', lang=lang), hide_input=True, confirmation_prompt=True)
    
    # pyuploader配置
    click.echo('\n--- pyuploader 配置 ---')
    pyuploader_repo = click.prompt(_('enter_pyuploader_repo', lang=lang), 
                                    default='https://upload.pypi.org/legacy/')
    pyuploader_username = click.prompt(_('enter_pyuploader_username', lang=lang), 
                                        default=pypi_username)
    use_same_password = click.confirm(_('use_same_password', lang=lang), default=True)
    pyuploader_password = pypi_password
    if not use_same_password:
        pyuploader_password = click.prompt(_('enter_pyuploader_password', lang=lang), 
                                            hide_input=True, confirmation_prompt=True)
    
    # 构建配置内容
    config_content = []
    config_content.append('# .pypirc configuration file\n')
    config_content.append('# 自动生成的PyPI上传配置\n')
    config_content.append('# 文件权限: 建议设置为600（chmod 600 ~/.pypirc）\n\n')
    
    config_content.append('[distutils]\n')
    config_content.append('index-servers =\n')
    config_content.append('    pypi\n')
    if include_testpypi:
        config_content.append('    testpypi\n')
    config_content.append('    pyuploader\n\n')
    
    # PyPI配置
    config_content.append('[pypi]\n')
    config_content.append('repository = https://upload.pypi.org/legacy/\n')
    config_content.append(f'username = {pypi_username}\n')
    config_content.append(f'password = {pypi_password}\n\n')
    
    # TestPyPI配置
    if include_testpypi:
        config_content.append('[testpypi]\n')
        config_content.append('repository = https://test.pypi.org/legacy/\n')
        config_content.append(f'username = {testpypi_username}\n')
        config_content.append(f'password = {testpypi_password}\n\n')
    
    # pyuploader配置
    config_content.append('[pyuploader]\n')
    config_content.append(f'repository = {pyuploader_repo}\n')
    config_content.append(f'username = {pyuploader_username}\n')
    config_content.append(f'password = {pyuploader_password}\n')
    
    # 写入文件
    try:
        with open(pypirc_path, 'w', encoding='utf-8') as f:
            f.writelines(config_content)
        
        # 设置文件权限为600（仅拥有者可读写）
        try:
            os.chmod(pypirc_path, 0o600)
            click.echo(_('pypirc_permissions_set', lang=lang))
        except Exception:
            click.echo(click.style(_('pypirc_permissions_warning', lang=lang), fg='yellow'))
        
        click.echo(click.style(_('pypirc_config_success', str(pypirc_path), lang=lang), fg='green'))
        click.echo(_('pypirc_config_next_steps', lang=lang))
    except Exception as e:
        click.echo(click.style(_('pypirc_config_failed', str(e), lang=lang), fg='red'))
        sys.exit(1)

# 设置别名，保持向后兼容
main = cli

# 在模块级别应用全局替换，确保中文模式下标题被汉化
# 保存原始方法
_original_write_usage = click.HelpFormatter.write_usage
_original_write_heading = click.HelpFormatter.write_heading

# 重写方法来实现汉化

def _chinese_write_usage(self, prog, args='', prefix='Usage: '):
    # 替换为中文标题
    _original_write_usage(self, prog, args, prefix='用法: ')


def _chinese_write_heading(self, heading):
    # 替换英文标题为中文
    if heading == 'Options':
        heading = '选项'
    elif heading == 'Commands':
        heading = '命令'
    _original_write_heading(self, heading)

# 默认使用中文标题
click.HelpFormatter.write_usage = _chinese_write_usage
click.HelpFormatter.write_heading = _chinese_write_heading

if __name__ == '__main__':
    cli()