#!/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 check_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 = [f.name for f in images_dir.iterdir() if f.is_file() and f.suffix.lower() in ['.jpg', '.jpeg', '.png']]
    
    print(f"检查球队 '{team_name}' 的球员图片匹配情况:")
    print(f"  球员数量: {players.count()}")
    print(f"  图片文件数量: {len(image_files)}")
    print("-" * 60)
    
    # 创建模糊匹配器
    matcher = FuzzyFilenameMatcher(threshold=0.8)
    
    matched_count = 0
    unmatched_players = []
    
    for player in players:
        try:
            match, score = matcher.fuzzy_match(player.name, image_files)
            print(f"✓ {player.name:<25} -> {match:<25} ({score:.2%})")
            matched_count += 1
        except ValueError as e:
            print(f"✗ {player.name:<25} -> 未匹配 ({e})")
            unmatched_players.append(player.name)
    
    print("-" * 60)
    print(f"匹配统计:")
    print(f"  成功匹配: {matched_count}/{players.count()} ({matched_count/players.count():.1%})")
    
    if unmatched_players:
        print(f"  未匹配球员:")
        for player_name in unmatched_players:
            print(f"    - {player_name}")
            
            # 显示最接近的匹配
            matches = matcher.get_all_matches(player_name, image_files)
            if matches:
                top_matches = matches[:3]
                print(f"      最接近的匹配:")
                for filename, score in top_matches:
                    status = "✓" if score >= matcher.threshold else "✗"
                    print(f"        {status} {filename} ({score:.2%})")


def check_all_teams():
    """
    检查所有球队的球员图片匹配情况
    """
    teams = Team.objects.all()
    
    print("检查所有球队的球员图片匹配情况:")
    print("=" * 60)
    
    for team in teams:
        check_team_player_images(team.name)
        print()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        # 检查指定球队
        team_name = sys.argv[1]
        check_team_player_images(team_name)
    else:
        # 检查所有球队
        check_all_teams()