"""
Check ODF Cumulative Results Structure

This script inspects the structure of odf_cumulative_results collection
to understand the actual field names and nested structure.
"""

from services.mongo import MongoService
from services.json_flattener import JSONFlattener
import json

def check_odf_structure():
    """Check the structure of odf_cumulative_results."""
    print("=" * 80)
    print("ODF Cumulative Results Structure 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 collection
    collection = mongo_service.db['odf_cumulative_results']
    
    # Get sample document
    print("\n2. Fetching sample document...")
    doc = collection.find_one()
    
    if not doc:
        print("❌ No documents found in collection")
        return False
    
    # Show top-level fields
    print("\n3. Top-level fields:")
    for field in sorted(doc.keys()):
        if field != '_id':
            value = doc[field]
            value_type = type(value).__name__
            print(f"   - {field}: {value_type}")
    
    # Show competitor structure
    print("\n4. Competitor structure:")
    if 'competitor' in doc:
        competitor = doc['competitor']
        print(f"   Type: {type(competitor).__name__}")
        if isinstance(competitor, dict):
            for key, value in competitor.items():
                print(f"   - competitor.{key}: {type(value).__name__}")
                if isinstance(value, dict):
                    for subkey in value.keys():
                        print(f"     - competitor.{key}.{subkey}")
    
    # Show odf_body structure
    print("\n5. ODF Body structure:")
    if 'odf_body' in doc:
        odf_body = doc['odf_body']
        print(f"   Type: {type(odf_body).__name__}")
        if isinstance(odf_body, dict):
            for key in sorted(odf_body.keys()):
                print(f"   - odf_body.{key}")
    
    # Flatten and show all fields
    print("\n6. All flattened fields:")
    flattener = JSONFlattener()
    flat = flattener.flatten(doc)
    
    print(f"   Total flattened fields: {len(flat)}")
    print("\n   Fields containing 'code':")
    for field in sorted(flat.keys()):
        if 'code' in field.lower():
            print(f"   - {field}: {flat[field]}")
    
    # Show sample document (truncated)
    print("\n7. Sample document (first 1000 chars):")
    del doc['_id']
    doc_str = json.dumps(doc, indent=2, default=str)
    print(doc_str[:1000])
    
    return True

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