#!/usr/bin/env python3
"""
Generate JavaScript team name to filename mapping from CSV
"""
import csv
import json

def generate_team_mappings():
    """Generate team name mappings from CSV - only default logos, no alternates"""
    mappings = {}
    seen_teams = set()  # Track which teams we've already mapped
    
    with open('cfb_mastersheet.csv', 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            flair_name = row.get('flair_name', '').strip()
            image_source = row.get('image_source', '').strip()
            abbreviated = row.get('flair_abbreviated', '').strip()
            default_flair = row.get('default_flair', '').strip()
            image_name = row.get('image_name', '').strip()
            
            # Only use default logos (default_flair == '1' or not an Alternate)
            is_alternate = 'Alternate' in image_name or default_flair == '0'
            
            if flair_name and image_source and image_source.startswith('cfb/') and not is_alternate:
                filename = image_source.replace('cfb/', '')
                
                # Only add if we haven't seen this team name yet (first match wins)
                if flair_name not in seen_teams:
                    mappings[flair_name] = filename
                    seen_teams.add(flair_name)
                
                # Also map abbreviated name (only if not already mapped)
                if abbreviated and abbreviated not in mappings:
                    mappings[abbreviated] = filename
                
                # Extract school name (without mascot) - only if not already mapped
                parts = flair_name.split()
                if len(parts) >= 2:
                    school_name = ' '.join(parts[:-1])
                    if school_name not in mappings:
                        mappings[school_name] = filename
    
    return mappings

if __name__ == '__main__':
    print("Generating team name mappings from CSV...")
    mappings = generate_team_mappings()
    
    # Write as JavaScript file
    with open('static/team_mappings.js', 'w') as f:
        f.write('// Team name to filename mappings generated from cfb_mastersheet.csv\n')
        f.write('const TEAM_NAME_MAPPINGS = {\n')
        for team_name, filename in sorted(mappings.items()):
            # Escape quotes in team names
            escaped_name = team_name.replace("'", "\\'").replace('"', '\\"')
            f.write(f"    '{escaped_name}': '{filename}',\n")
        f.write('};\n\n')
        f.write('// Function to get filename from team name\n')
        f.write('function getTeamFilename(teamName) {\n')
        f.write('    // Try exact match first\n')
        f.write('    if (TEAM_NAME_MAPPINGS[teamName]) {\n')
        f.write('        return TEAM_NAME_MAPPINGS[teamName];\n')
        f.write('    }\n')
        f.write('    // Try case-insensitive match\n')
        f.write('    for (const [key, value] of Object.entries(TEAM_NAME_MAPPINGS)) {\n')
        f.write('        if (key.toLowerCase() === teamName.toLowerCase()) {\n')
        f.write('            return value;\n')
        f.write('        }\n')
        f.write('    }\n')
        f.write('    // Fallback to simple conversion\n')
        f.write('    return teamName.toLowerCase().replace(/\\s+/g, "").replace(/[^a-z0-9]/g, "");\n')
        f.write('}\n')
    
    print(f"✓ Generated static/team_mappings.js with {len(mappings)} mappings")
    print("\nTo use in your HTML, add:")
    print('  <script src="team_mappings.js"></script>')
    print('  before your main script.js')

