"""
Test Exact Matches Display

This script tests if exact matches are correctly displayed after the fix.
"""

from services.mongo import MongoService
from services.json_loader import JSONLoader
from services.diff_engine import DiffEngine
from services.import_preview_engine import ImportPreviewEngine
from services.settings_service import SettingsService

def test_exact_matches_display():
    """Test exact matches display."""
    print("=" * 80)
    print("Exact Matches Display Test")
    print("=" * 80)
    
    # Initialize services
    print("\n1. Initializing services...")
    settings_service = SettingsService()
    config = settings_service.config
    
    mongo_service = MongoService()
    if not mongo_service.connect():
        print("❌ Failed to connect to MongoDB")
        return False
    
    json_loader = JSONLoader(
        config['json_sources']['base_path'],
        config['collections']
    )
    
    diff_engine = DiffEngine(config['collections'])
    preview_engine = ImportPreviewEngine()
    
    print("✅ Services initialized")
    
    # Test with odf_rankings
    collection_name = 'odf_rankings'
    
    print(f"\n2. Loading data for {collection_name}...")
    sources = json_loader.get_available_sources()
    source_name = sources[0]
    
    json_records = json_loader.load_collection_from_source(collection_name, source_name)
    print(f"   Loaded {len(json_records)} JSON records")
    
    collection = mongo_service.get_collection(collection_name)
    db_records = list(collection.find().limit(100))
    print(f"   Loaded {len(db_records)} MongoDB records")
    
    # Run comparison
    print("\n3. Running comparison...")
    results = diff_engine.compare_collections(
        collection_name,
        json_records,
        db_records
    )
    
    exact_matches = results['exact_matches']
    print(f"   Found {len(exact_matches)} exact matches")
    
    if not exact_matches:
        print("\n❌ No exact matches found - cannot test display")
        return False
    
    # Test preview DataFrame building
    print("\n4. Testing preview DataFrame building...")
    print(f"   Exact matches structure:")
    sample = exact_matches[0]
    print(f"   - Type: {type(sample).__name__}")
    print(f"   - Has 'json_record' key: {'json_record' in sample}")
    print(f"   - Keys (first 5): {list(sample.keys())[:5]}")
    
    # Build preview DataFrame
    df = preview_engine.build_preview_dataframe(exact_matches, 'exact')
    
    print(f"\n5. Preview DataFrame results:")
    print(f"   - DataFrame shape: {df.shape}")
    print(f"   - Is empty: {df.empty}")
    
    if df.empty:
        print("\n❌ FAILED: DataFrame is empty!")
        return False
    
    print(f"   - Columns (first 10): {list(df.columns)[:10]}")
    print(f"   - Sample row:")
    for col in list(df.columns)[:5]:
        print(f"     {col}: {df[col].iloc[0]}")
    
    # Remove metadata columns
    display_df = df.drop(columns=[c for c in df.columns if c.startswith('_')], errors='ignore')
    print(f"\n   - Display DataFrame shape: {display_df.shape}")
    print(f"   - Display columns (first 10): {list(display_df.columns)[:10]}")
    
    print("\n" + "=" * 80)
    print("✅ SUCCESS! Exact matches DataFrame is built correctly")
    print("=" * 80)
    
    return True

if __name__ == "__main__":
    try:
        success = test_exact_matches_display()
        exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
        exit(1)
