#!/usr/bin/env python
"""
详细检查球员图片匹配情况
"""

import requests
import os
import json
from pathlib import Path

# Django服务器地址
BASE_URL = "http://127.0.0.1:8000"
API_BASE_URL = f"{BASE_URL}/api"

def check_api_endpoint(endpoint):
    """检查API端点是否可访问"""
    try:
        response = requests.get(f"{API_BASE_URL}/{endpoint}", timeout=10)
        return response.status_code == 200, response.status_code, response.json() if response.status_code == 200 else None
    except Exception as e:
        return False, str(e), None

def get_actual_image_files(team_name):
    """获取球队实际存在的图片文件"""
    image_dir = f"media/team_player_images/{team_name}"
    image_files = {}
    
    if os.path.exists(image_dir):
        for file in os.listdir(image_dir):
            if file.endswith('.jpg'):
                # 移除.jpg扩展名并替换下划线为空格，作为可能的球员名
                player_name = file[:-4].replace('_', ' ')
                image_files[player_name] = file
    
    return image_files

def normalize_player_name(name):
    """标准化球员名称以进行匹配"""
    # 移除特殊字符和空格处理
    normalized = name.replace('_', ' ')
    # 处理常见的特殊字符映射
    char_map = {
        'Ã¸': 'ø',
        'Ã©': 'é',
        'Ã¤': 'ä',
        'Ã¡': 'á',
        'Ã³': 'ó',
        'Ã±': 'ñ',
        'â€™': "'",
        'Ã': 'Á',
        'Ã¶': 'ö',
        'Ã¼': 'ü',
        'Ã§': 'ç',
        'Ã¯': 'ï',
        'Ãª': 'ê',
        'Ã¢': 'â'
    }
    
    for old_char, new_char in char_map.items():
        normalized = normalized.replace(old_char, new_char)
    
    return normalized

def main():
    print("开始详细检查球员图片匹配情况...\n")
    
    # 获取测试数据
    print("1. 获取测试数据:")
    success, status, countries_data = check_api_endpoint("countries/")
    if not success:
        print("   无法获取国家数据，终止检查")
        return
        
    if not countries_data or 'results' not in countries_data or not countries_data['results']:
        print("   没有国家数据，终止检查")
        return
        
    country_id = countries_data['results'][0]['id']
    print(f"   使用国家ID: {country_id}")
    
    # 获取球队数据
    success, status, teams_data = check_api_endpoint(f"teams/?country={country_id}")
    if not success or not teams_data or 'results' not in teams_data or not teams_data['results']:
        print("   无法获取球队数据，终止检查")
        return
        
    team = teams_data['results'][0]
    team_id = team['id']
    team_name = team['name']
    print(f"   使用球队: {team_name} (ID: {team_id})")
    
    # 获取球员数据
    success, status, players_data = check_api_endpoint(f"players/?team={team_id}")
    if not success or not players_data or 'results' not in players_data or not players_data['results']:
        print("   无法获取球员数据，终止检查")
        return
        
    print(f"   球员数量: {len(players_data['results'])}")
    
    # 获取实际图片文件
    actual_images = get_actual_image_files(team_name)
    print(f"   实际存在的图片文件数量: {len(actual_images)}")
    print()
    
    # 检查匹配情况
    print("2. 球员与图片匹配情况:")
    matched = 0
    unmatched = 0
    
    # 显示所有实际存在的图片文件
    print("   实际存在的图片文件:")
    for player_name, file_name in list(actual_images.items())[:10]:
        print(f"     {file_name} -> {player_name}")
    if len(actual_images) > 10:
        print(f"     ... 还有 {len(actual_images) - 10} 个文件")
    print()
    
    # 检查球员数据与图片文件的匹配
    print("   球员数据与图片匹配:")
    for player in players_data['results'][:20]:  # 检查前20个球员
        player_name = player['name']
        normalized_name = normalize_player_name(player_name)
        
        # 直接匹配
        if player_name in actual_images:
            print(f"   ✓ {player_name} -> {actual_images[player_name]}")
            matched += 1
        elif normalized_name in actual_images:
            print(f"   ✓ {player_name} (标准化后) -> {actual_images[normalized_name]}")
            matched += 1
        else:
            # 尝试模糊匹配
            found = False
            for img_player_name in actual_images:
                # 简单的模糊匹配：检查是否包含相同的关键字
                if player_name.split()[-1] in img_player_name or img_player_name.split()[-1] in player_name:
                    print(f"   ~ {player_name} (模糊匹配) -> {actual_images[img_player_name]}")
                    matched += 1
                    found = True
                    break
            
            if not found:
                print(f"   ✗ {player_name} -> 未找到匹配的图片")
                unmatched += 1
    
    print(f"\n   匹配结果: {matched} 个球员匹配成功, {unmatched} 个球员未匹配")
    
    # 显示未使用的图片
    print("\n3. 未使用的图片文件:")
    used_images = set()
    for player in players_data['results']:
        player_name = player['name']
        normalized_name = normalize_player_name(player_name)
        if player_name in actual_images:
            used_images.add(actual_images[player_name])
        elif normalized_name in actual_images:
            used_images.add(actual_images[normalized_name])
    
    unused_images = set(actual_images.values()) - used_images
    if unused_images:
        for image in list(unused_images)[:10]:
            print(f"     {image}")
        if len(unused_images) > 10:
            print(f"     ... 还有 {len(unused_images) - 10} 个未使用的文件")
        print(f"   总共 {len(unused_images)} 个未使用的图片文件")
    else:
        print("   没有未使用的图片文件")

if __name__ == "__main__":
    main()