"""
Inspect Data Script

This script inspects the structure of documents in collections
to understand how to properly check relationships.
"""

from services.mongo import MongoService
import json

def inspect_data():
    """Inspect data structure in collections."""
    print("=" * 80)
    print("Data Structure Inspector")
    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")
    
    # Collections to inspect
    collections = [
        'people',
        'participants', 
        'organisations',
        'odf_cumulative_results',
        'odf_rankings',
        'odf_medallists'
    ]
    
    for collection_name in collections:
        print("\n" + "=" * 80)
        print(f"Collection: {collection_name}")
        print("=" * 80)
        
        try:
            collection = mongo_service.db[collection_name]
            count = collection.count_documents({})
            print(f"Total documents: {count}")
            
            if count > 0:
                # Get first document
                doc = collection.find_one()
                
                # Remove _id for cleaner output
                if '_id' in doc:
                    del doc['_id']
                
                # Print structure
                print("\nSample document structure:")
                print(json.dumps(doc, indent=2, default=str)[:1500])  # First 1500 chars
                
                # Show available fields
                print("\nAvailable fields:")
                fields = list(doc.keys())
                for field in fields[:20]:  # First 20 fields
                    value = doc.get(field)
                    value_type = type(value).__name__
                    if isinstance(value, dict):
                        print(f"  - {field}: {value_type} (keys: {', '.join(list(value.keys())[:5])})")
                    elif isinstance(value, list):
                        print(f"  - {field}: {value_type} (length: {len(value)})")
                    else:
                        print(f"  - {field}: {value_type}")
        
        except Exception as e:
            print(f"❌ Error inspecting {collection_name}: {e}")
    
    print("\n" + "=" * 80)
    return True

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