#!/usr/bin/env python
"""
重命名球员图片文件脚本
将图片文件名调整为与数据库中的球员名称一致，提高匹配准确性
"""

import os
import django
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).resolve().parent
sys.path.insert(0, str(project_root))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.project_config.settings')
django.setup()

from api.models import Player, Team
from fuzzy_filename_matcher import FuzzyFilenameMatcher


def rename_team_player_images(team_name):
    """
    重命名指定球队的球员图片文件
    
    Args:
        team_name (str): 球队名称
    """
    try:
        team = Team.objects.get(name=team_name)
    except Team.DoesNotExist:
        print(f"球队 '{team_name}' 不存在")
        return
    
    # 获取该球队的所有球员
    players = Player.objects.filter(stats__team=team).distinct()
    
    # 获取该球队的图片文件列表
    images_dir = project_root / 'media' / 'team_player_images' / team_name
    if not images_dir.exists():
        print(f"图片目录 '{images_dir}' 不存在")
        return
    
    image_files = list(images_dir.iterdir())
    
    print(f"重命名球队 '{team_name}' 的球员图片文件:")
    print(f"  球员数量: {players.count()}")
    print(f"  图片文件数量: {len(image_files)}")
    print("-" * 60)
    
    # 创建模糊匹配器
    matcher = FuzzyFilenameMatcher(threshold=0.8)
    
    renamed_count = 0
    
    for player in players:
        try:
            # 获取匹配的文件
            match, score = matcher.fuzzy_match(player.name, [f.name for f in image_files])
            
            # 构造期望的文件名
            expected_name = player.name.replace(' ', '_') + Path(match).suffix
            
            # 如果文件名不匹配，则重命名
            if match != expected_name:
                old_path = images_dir / match
                new_path = images_dir / expected_name
                
                # 检查目标文件是否已存在
                if new_path.exists():
                    print(f"  跳过 '{match}' -> '{expected_name}' (目标文件已存在)")
                else:
                    old_path.rename(new_path)
                    print(f"  重命名 '{match}' -> '{expected_name}' (相似度: {score:.2%})")
                    renamed_count += 1
            else:
                print(f"  ✓ '{match}' 文件名已符合要求")
                
        except ValueError as e:
            print(f"  ✗ 未找到球员 '{player.name}' 的匹配图片文件")
    
    print("-" * 60)
    print(f"重命名完成，共重命名 {renamed_count} 个文件")


def rename_all_teams_player_images():
    """
    重命名所有球队的球员图片文件
    """
    teams = Team.objects.all()
    
    print("重命名所有球队的球员图片文件:")
    print("=" * 60)
    
    for team in teams:
        rename_team_player_images(team.name)
        print()


def standardize_special_characters_in_filenames():
    """
    标准化文件名中的特殊字符
    将文件系统中的特殊字符转换为与数据库一致的格式
    """
    teams = Team.objects.all()
    char_mapping = {
        'ã': 'a',
        'é': 'e',
        'í': 'i',
        'ó': 'o',
        'ú': 'u',
        'á': 'a',
        'É': 'E',
        'ø': 'o',
        'Ø': 'O',
        'ü': 'u',
        'ñ': 'n',
        'ä': 'a',
        'ö': 'o',
        'ç': 'c',
    }
    
    print("标准化所有球队球员图片文件名中的特殊字符:")
    print("=" * 60)
    
    standardized_count = 0
    
    for team in teams:
        images_dir = project_root / 'media' / 'team_player_images' / team.name
        if not images_dir.exists():
            continue
            
        print(f"处理球队 '{team.name}':")
        
        for image_file in images_dir.iterdir():
            if not image_file.is_file():
                continue
                
            original_name = image_file.name
            new_name = original_name
            
            # 替换特殊字符
            for old_char, new_char in char_mapping.items():
                new_name = new_name.replace(old_char, new_char)
            
            # 如果文件名发生了变化，则重命名
            if new_name != original_name:
                old_path = image_file
                new_path = image_file.parent / new_name
                
                # 检查目标文件是否已存在
                if new_path.exists():
                    print(f"  跳过 '{original_name}' -> '{new_name}' (目标文件已存在)")
                else:
                    old_path.rename(new_path)
                    print(f"  标准化 '{original_name}' -> '{new_name}'")
                    standardized_count += 1
    
    print("=" * 60)
    print(f"标准化完成，共处理 {standardized_count} 个文件")


def main():
    """
    主函数
    """
    if len(sys.argv) > 1:
        if sys.argv[1] == '--all':
            # 重命名所有球队的图片文件
            rename_all_teams_player_images()
        elif sys.argv[1] == '--standardize':
            # 标准化特殊字符
            standardize_special_characters_in_filenames()
        else:
            # 重命名单个球队的图片文件
            team_name = sys.argv[1]
            rename_team_player_images(team_name)
    else:
        print("用法:")
        print("  python rename_player_images.py <球队名称>     # 重命名单个球队的图片文件")
        print("  python rename_player_images.py --all          # 重命名所有球队的图片文件")
        print("  python rename_player_images.py --standardize   # 标准化所有文件名中的特殊字符")


if __name__ == "__main__":
    main()