"""
Check People Import Status

This script checks the people collection after import to verify:
1. How many records exist
2. Whether they have code/codes fields
3. Sample data structure
"""

from services.mongo import MongoService
import json

def check_people_import():
    """Check people collection status after import."""
    print("=" * 80)
    print("People Collection Import Check")
    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 people collection
    people_collection = mongo_service.db['people']
    
    # Total count
    total_count = people_collection.count_documents({})
    print(f"\n2. Total people records: {total_count}")
    
    # Check for code field
    with_code = people_collection.count_documents({'code': {'$exists': True, '$ne': None}})
    print(f"   Records with 'code' field: {with_code}")
    
    # Check for codes array
    with_codes_array = people_collection.count_documents({'codes': {'$exists': True}})
    print(f"   Records with 'codes' array: {with_codes_array}")
    
    # Check for given_name/family_name (athlete fields)
    with_athlete_fields = people_collection.count_documents({
        'given_name': {'$exists': True},
        'family_name': {'$exists': True}
    })
    print(f"   Records with athlete fields (given_name, family_name): {with_athlete_fields}")
    
    # Show sample with code
    print("\n3. Sample records:")
    
    if with_code > 0:
        print("\n   ✅ Sample person WITH code:")
        person = people_collection.find_one({'code': {'$exists': True, '$ne': None}})
        if person:
            del person['_id']
            print(json.dumps(person, indent=4, default=str)[:800])
    
    if with_athlete_fields > 0:
        print("\n   📋 Sample person with athlete fields:")
        person = people_collection.find_one({
            'given_name': {'$exists': True},
            'family_name': {'$exists': True}
        })
        if person:
            del person['_id']
            print(json.dumps(person, indent=4, default=str)[:800])
    
    # Show sample without code (old records)
    print("\n   📋 Sample person WITHOUT code (old record):")
    person = people_collection.find_one({'code': {'$exists': False}})
    if person:
        del person['_id']
        fields = list(person.keys())[:15]
        print(f"   Fields: {', '.join(fields)}")
    
    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    
    if with_code == 0 and with_athlete_fields == 0:
        print("\n❌ PROBLEM: No athlete data found in people collection!")
        print("\nPossible reasons:")
        print("1. You imported to the wrong collection")
        print("2. The JSON data doesn't have code/given_name/family_name fields")
        print("3. Import failed silently")
        print("\n💡 Solution:")
        print("- Check which collection you selected during import")
        print("- Verify JSON source has participant/athlete data")
        print("- Try importing again with correct settings")
    elif with_codes_array > 0:
        print(f"\n✅ SUCCESS! Found {with_codes_array} athletes with codes array")
        print("   Automatic consolidation is working!")
    elif with_code > 0:
        print(f"\n⚠️  Found {with_code} athletes with code field")
        print("   But no codes array - consolidation may not have run")
    else:
        print(f"\n⚠️  Found {with_athlete_fields} records with athlete fields")
        print("   But no code field - data structure may be different")
    
    return True

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