"""
Sync People from ODF Collections

This script extracts athlete information from ODF collections
and adds missing people to the people collection.
"""

from services.mongo import MongoService
from datetime import datetime

def sync_people_from_odf():
    """Sync people data from ODF collections."""
    print("=" * 80)
    print("Sync People from ODF Collections")
    print("=" * 80)
    
    # Initialize MongoDB service
    print("\n1. Connecting to MongoDB...")
    mongo_service = MongoService()
    
    if not mongo_service.connect():
        print("❌ Failed to connect to MongoDB")
        return False
    
    print("✅ Connected to MongoDB")
    
    # Get existing people codes
    print("\n2. Loading existing people codes...")
    people_collection = mongo_service.db['people']
    existing_codes = set()
    
    for person in people_collection.find({}, {'code': 1}):
        if 'code' in person and person['code']:
            existing_codes.add(str(person['code']))
    
    print(f"✅ Found {len(existing_codes)} existing people")
    
    # Collections to extract athlete data from
    odf_collections = [
        'odf_cumulative_results',
        'odf_rankings',
        'odf_medallists',
        'odf_results'
    ]
    
    # Extract athlete data
    print("\n3. Extracting athlete data from ODF collections...")
    athletes_to_add = {}
    
    for collection_name in odf_collections:
        try:
            collection = mongo_service.db[collection_name]
            count = collection.count_documents({})
            
            if count == 0:
                print(f"   ℹ️  {collection_name}: empty")
                continue
            
            print(f"   📋 Processing {collection_name}...")
            
            processed = 0
            errors = 0
            
            for doc in collection.find():
                try:
                    processed += 1
                    
                    # Navigate to athlete data
                    competitor = doc.get('competitor', {})
                    if not competitor or not isinstance(competitor, dict):
                        continue
                    
                    composition = competitor.get('composition', {})
                    
                    # Composition can be a dict or list
                    if isinstance(composition, list):
                        # If it's a list, take the first item
                        composition = composition[0] if composition else {}
                    
                    if not isinstance(composition, dict):
                        continue
                    
                    athlete = composition.get('athlete', {})
                    if not athlete or not isinstance(athlete, dict):
                        continue
                    
                    description = athlete.get('description', {})
                    
                    if not description or not isinstance(description, dict):
                        continue
                    
                    # Get athlete code
                    code = athlete.get('code')
                    if not code:
                        continue
                except Exception as e:
                    errors += 1
                    if errors <= 3:  # Show first 3 errors
                        print(f"      ⚠️  Error in document: {e}")
                    continue
                
                code_str = str(int(code)) if isinstance(code, (int, float)) else str(code)
                
                # Skip if already exists
                if code_str in existing_codes:
                    continue
                
                # Skip if already in our list
                if code_str in athletes_to_add:
                    continue
                
                # Extract athlete information
                athlete_data = {
                    'code': code_str,
                    'given_name': description.get('given_name', ''),
                    'family_name': description.get('family_name', ''),
                    'gender': description.get('gender', ''),
                    'organisation': description.get('organisation', ''),
                    'birth_date': description.get('birth_date', ''),
                    'print_name': f"{description.get('family_name', '').upper()} {description.get('given_name', '')}",
                    'current': 'True',
                    'metadata': {
                        'source': 'odf_sync',
                        'synced_at': datetime.utcnow().isoformat(),
                        'synced_from': collection_name
                    }
                }
                
                athletes_to_add[code_str] = athlete_data
            
            print(f"      Found {len([a for a in athletes_to_add.values() if a['metadata']['synced_from'] == collection_name])} new athletes")
        
        except Exception as e:
            print(f"   ❌ Error processing {collection_name}: {e}")
    
    # Summary
    print(f"\n4. Summary:")
    print(f"   📊 Total new athletes to add: {len(athletes_to_add)}")
    
    if len(athletes_to_add) == 0:
        print("\n✅ No new athletes to add. All ODF athletes already exist in people collection.")
        return True
    
    # Show sample
    print("\n   Sample athletes to add:")
    for i, (code, athlete) in enumerate(list(athletes_to_add.items())[:5]):
        print(f"      {i+1}. {athlete['given_name']} {athlete['family_name']} (code: {code}, org: {athlete['organisation']})")
    
    # Ask for confirmation
    print("\n" + "=" * 80)
    response = input("Do you want to add these athletes to the people collection? (yes/no): ")
    
    if response.lower() not in ['yes', 'y']:
        print("❌ Operation cancelled")
        return False
    
    # Insert athletes
    print("\n5. Inserting athletes into people collection...")
    
    try:
        athletes_list = list(athletes_to_add.values())
        result = people_collection.insert_many(athletes_list)
        
        print(f"✅ Successfully inserted {len(result.inserted_ids)} athletes")
        print("\n" + "=" * 80)
        print("SUCCESS! Athletes have been synced from ODF collections.")
        print("=" * 80)
        
        # Verify
        new_count = people_collection.count_documents({})
        print(f"\nTotal people in collection: {new_count}")
        
        return True
    
    except Exception as e:
        print(f"❌ Error inserting athletes: {e}")
        return False

if __name__ == "__main__":
    try:
        sync_people_from_odf()
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
