import os
import shutil
from pathlib import Path

# 定义路径
data_dir = Path(r'C:\Users\jerry\PyCharmProjects\footviz\footviz\data')
countries_dir = data_dir / 'countries'
matches_dir = data_dir / 'matches'
team_data_dir = data_dir / 'team_data'
players_dir = data_dir / 'players'
player_data_backup_dir = data_dir / 'player_data_backup'

print("开始整合所有数据到 countries 目录...")

# 1. 整合 matches 目录中的数据
print("\n1. 整合 matches 目录中的数据...")
if matches_dir.exists():
    country_mapping = {
        'france': 'France',
        'germany': 'Germany',
        'spain': 'Spain',
        'uk': 'England'
    }
    
    for old_country, new_country in country_mapping.items():
        old_country_path = matches_dir / old_country
        new_country_path = countries_dir / new_country
        
        if old_country_path.exists() and new_country_path.exists():
            # 移动所有球队的 matches.csv 文件
            for team_file in old_country_path.iterdir():
                if team_file.suffix == '.csv':
                    team_name = team_file.stem
                    team_dir = new_country_path / team_name
                    if team_dir.exists():
                        destination = team_dir / 'matches.csv'
                        shutil.move(str(team_file), str(destination))
                        print(f"  移动 {old_country}/{team_file.name} 到 {new_country}/{team_name}/matches.csv")
    
    # 删除空的 matches 目录
    shutil.rmtree(matches_dir)
    print("  删除原始 matches 目录")

# 2. 整合 team_data 目录中的 HTML 文件
print("\n2. 整合 team_data 目录中的 HTML 文件...")
if team_data_dir.exists():
    for team_file in team_data_dir.iterdir():
        if team_file.suffix == '.html' and '_goals_vs_assists' in team_file.name:
            # 提取球队名称
            team_name = team_file.name.replace('_goals_vs_assists.html', '')
            
            # 查找对应的国家和球队目录
            found = False
            for country_dir in countries_dir.iterdir():
                if country_dir.is_dir() and country_dir.name != 'China':  # China 是后来添加的，没有球队
                    team_dir = country_dir / team_name
                    if team_dir.exists():
                        # 创建 html 目录并移动文件
                        html_dir = team_dir / 'html'
                        html_dir.mkdir(exist_ok=True)
                        destination = html_dir / team_file.name
                        shutil.move(str(team_file), str(destination))
                        print(f"  移动 {team_file.name} 到 {country_dir.name}/{team_name}/html/{team_file.name}")
                        found = True
                        break
            
            if not found:
                print(f"  未找到对应的球队目录: {team_name}")
    
    # 删除空的 team_data 目录（如果为空）
    try:
        team_data_dir.rmdir()
        print("  删除空的 team_data 目录")
    except OSError:
        print("  team_data 目录不为空，保留")

# 3. 整合 players 目录中的数据
print("\n3. 整合 players 目录中的数据...")
players_teams_dir = players_dir / 'teams'
if players_teams_dir.exists():
    for team_dir in players_teams_dir.iterdir():
        if team_dir.is_dir():
            team_name = team_dir.name
            
            # 查找对应的国家和球队目录
            found = False
            for country_dir in countries_dir.iterdir():
                if country_dir.is_dir() and country_dir.name != 'China':
                    target_team_dir = country_dir / team_name
                    if target_team_dir.exists():
                        # 移动 players 目录
                        target_players_dir = target_team_dir / 'players'
                        if target_players_dir.exists():
                            # 如果目标目录已存在，则合并文件
                            for player_file in team_dir.iterdir():
                                if player_file.is_file():
                                    destination = target_players_dir / player_file.name
                                    shutil.move(str(player_file), str(destination))
                            print(f"  合并 {team_name} 的球员数据到 {country_dir.name}/{team_name}/players/")
                        else:
                            # 直接移动整个目录
                            shutil.move(str(team_dir), str(target_players_dir))
                            print(f"  移动 {team_name} 的球员数据到 {country_dir.name}/{team_name}/players/")
                        found = True
                        break
            
            if not found:
                print(f"  未找到对应的球队目录: {team_name}")
    
    # 删除空的 players 目录
    try:
        shutil.rmtree(players_dir)
        print("  删除原始 players 目录")
    except:
        print("  无法删除 players 目录")

# 4. 处理 player_data_backup 目录
print("\n4. 处理 player_data_backup 目录...")
if player_data_backup_dir.exists():
    # 删除备份目录（因为数据已经在正确的位置了）
    shutil.rmtree(player_data_backup_dir)
    print("  删除 player_data_backup 目录（数据冗余）")

print("\n数据整合完成！")

# 显示新的目录结构示例
print("\n新的目录结构示例:")
countries = [d for d in countries_dir.iterdir() if d.is_dir()]
for country_dir in countries[:3]:  # 只显示前3个国家作为示例
    print(f"  {country_dir.name}/")
    teams = [d for d in country_dir.iterdir() if d.is_dir()]
    for team_dir in teams[:2]:  # 每个国家只显示前2个球队
        print(f"    {team_dir.name}/")
        for item in team_dir.iterdir():
            if item.is_file():
                print(f"      {item.name}")
            elif item.is_dir():
                print(f"      {item.name}/")
                sub_items = list(item.iterdir())
                for sub_item in sub_items[:2]:  # 每个子目录只显示前2个项目
                    print(f"        {sub_item.name}")
                if len(sub_items) > 2:
                    print(f"        ...")
    if len(teams) > 2:
        print("      ...")
if len(countries) > 3:
    print("  ...")