#!/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


def rename_images_to_match_database():
    """
    重命名图片文件，使其与数据库中的球员名称完全一致
    """
    teams = Team.objects.all()
    
    print("同步球员图片文件名与数据库记录...")
    print("=" * 60)
    
    renamed_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}':")
        
        # 获取该球队的所有球员
        players = Player.objects.filter(stats__team=team).distinct()
        
        for player in players:
            # 数据库中的标准名称（将空格替换为下划线）
            expected_filename = player.name.replace(' ', '_') + '.jpg'
            
            # 查找可能的现有文件（使用模糊匹配）
            existing_files = list(images_dir.glob(f"*{player.name.split()[-1]}*.jpg"))  # 按姓氏匹配
            if not existing_files:
                # 如果按姓氏找不到，尝试更宽松的匹配
                existing_files = list(images_dir.glob(f"*{player.name.split()[0]}*.jpg"))  # 按名字匹配
            
            if existing_files:
                # 如果找到了现有文件
                existing_file = existing_files[0]  # 取第一个匹配的文件
                
                # 如果文件名不匹配，则重命名
                if existing_file.name != expected_filename:
                    new_path = images_dir / expected_filename
                    
                    # 检查目标文件是否已存在
                    if new_path.exists():
                        print(f"  跳过 '{existing_file.name}' -> '{expected_filename}' (目标文件已存在)")
                    else:
                        existing_file.rename(new_path)
                        print(f"  重命名 '{existing_file.name}' -> '{expected_filename}'")
                        renamed_count += 1
                else:
                    print(f"  ✓ '{expected_filename}' 文件名已符合要求")
            else:
                print(f"  ✗ 未找到球员 '{player.name}' 的图片文件")
    
    print("=" * 60)
    print(f"同步完成，共重命名 {renamed_count} 个文件")


def restore_standardized_filenames():
    """
    恢复标准化的文件名（移除特殊字符）
    这是为了文件系统的兼容性和一致性
    """
    teams = Team.objects.all()
    char_mapping = {
        'á': 'a', 'à': 'a', 'â': 'a', 'ä': 'a', 'ã': 'a', 'å': 'a',
        'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
        'í': 'i', 'ì': 'i', 'î': 'i', 'ï': 'i',
        'ó': 'o', 'ò': 'o', 'ô': 'o', 'ö': 'o', 'õ': 'o', 'ø': 'o',
        'ú': 'u', 'ù': 'u', 'û': 'u', 'ü': 'u',
        'ý': 'y', 'ÿ': 'y',
        'ñ': 'n', 'ç': 'c',
        'Á': 'A', 'À': 'A', 'Â': 'A', 'Ä': 'A', 'Ã': 'A', 'Å': 'A',
        'É': 'E', 'È': 'E', 'Ê': 'E', 'Ë': 'E',
        'Í': 'I', 'Ì': 'I', 'Î': 'I', 'Ï': 'I',
        'Ó': 'O', 'Ò': 'O', 'Ô': 'O', 'Ö': 'O', 'Õ': 'O', 'Ø': 'O',
        'Ú': 'U', 'Ù': 'U', 'Û': 'U', 'Ü': 'U',
        'Ý': 'Y', 'Ÿ': 'Y',
        'Ñ': 'N', 'Ç': '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 '--restore' in sys.argv:
        # 恢复标准化的文件名
        restore_standardized_filenames()
    else:
        # 同步图片文件名与数据库记录
        rename_images_to_match_database()


if __name__ == "__main__":
    main()