import os
import shutil
import re

# Define the paths
player_data_dir = r'C:\Users\jerry\PyCharmProjects\footviz\footviz\data\player_data'
teams_dir = r'C:\Users\jerry\PyCharmProjects\footviz\footviz\data\players\teams'

# Standard team names mapping
team_name_mapping = {
    'Arsenal': 'Arsenal',
    'Aston Villa': 'Aston Villa',
    'Bournemouth': 'Bournemouth',
    'Brentford': 'Brentford',
    'Brighton': 'Brighton',
    'Chelsea': 'Chelsea',
    'Crystal Palace': 'Crystal Palace',
    'Everton': 'Everton',
    'Fulham': 'Fulham',
    'Ipswich': 'Ipswich',
    'Leicester': 'Leicester',
    'Liverpool': 'Liverpool',
    'Manchester City': 'Manchester City',
    'Man City': 'Manchester City',
    'Manchester United': 'Manchester United',
    'Man United': 'Manchester United',
    'Newcastle': 'Newcastle',
    'Nottingham Forest': 'Nottingham Forest',
    'Nott\'m Forest': 'Nottingham Forest',
    'Southampton': 'Southampton',
    'Tottenham': 'Tottenham',
    'Spurs': 'Tottenham',
    'West Ham': 'West Ham',
    'Wolves': 'Wolves',
    'Wolverhampton': 'Wolves'
}

# Get all player files
player_files = [f for f in os.listdir(player_data_dir) if f.endswith('.csv') and '_' in f]

print(f"Found {len(player_files)} player files to organize.")

# Process each player file
for filename in player_files:
    # Extract team name from filename (everything before the first underscore)
    team_name = filename.split('_')[0]
    
    # Check if team name needs to be standardized
    if team_name in team_name_mapping:
        standard_team_name = team_name_mapping[team_name]
    else:
        standard_team_name = team_name
    
    # Create team directory if it doesn't exist
    team_dir = os.path.join(teams_dir, standard_team_name)
    if not os.path.exists(team_dir):
        os.makedirs(team_dir)
        print(f"Created directory for team: {standard_team_name}")
    
    # Move file to team directory
    source_path = os.path.join(player_data_dir, filename)
    dest_path = os.path.join(team_dir, filename)
    
    # If file already exists in destination, we'll overwrite it
    if os.path.exists(dest_path):
        print(f"Overwriting existing file: {filename}")
        os.remove(dest_path)
    
    shutil.move(source_path, dest_path)
    print(f"Moved {filename} to {standard_team_name} folder")

print("Player file organization complete!")