use anyhow::Result;
use rag_module::RagModule;
use rag_module::services::search_service::EstateSearchOptions;

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔧 Testing Search WITHOUT Metadata Filters");
    
    // Test with existing estate data
    let mut estate_rag = RagModule::new("./example-enhanced-estate-data").await?;
    estate_rag.initialize().await?;
    estate_rag.set_user_context("estate_user_example").await?;
    
    println!("✅ RAG Module initialized");
    
    // Check collection health
    let health = estate_rag.collection_manager.get_collections_health().await?;
    println!("📊 Collection Health:");
    println!("   Estate Collection: {} points", health.aws_estate.points_count);
    
    // Test estate search WITHOUT any metadata filters (should work)
    let search_options = EstateSearchOptions {
        resource_types: None,    // No filter
        account_ids: None,       // No filter
        regions: None,           // No filter
        services: None,          // No filter
        states: None,            // No filter
        environment: None,
        application: None,
        synced_after: None,
        limit: Some(10),
        score_threshold: Some(0.05), // Very low threshold
        include_metadata: true,
        use_anonymous_ids: false,
    };
    
    println!("\n🔍 Testing estate search WITHOUT metadata filters...");
    let results = estate_rag.search_service
        .search_estate_resources("AWS EC2 instances", search_options, None)
        .await?;
    
    println!("✅ Estate Search Results (No Filters): {}", results.len());
    for (i, result) in results.iter().take(3).enumerate() {
        println!("   {}. Result keys: {:?}", i + 1, result.as_object().unwrap().keys().collect::<Vec<_>>());
        
        if let Some(score) = result.get("score").and_then(|v| v.as_f64()) {
            println!("      Score: {:.4}", score);
        }
    }
    
    // Now test with filters to confirm the issue
    let filtered_search_options = EstateSearchOptions {
        resource_types: None,
        account_ids: None,
        regions: Some(vec!["us-east-1".to_string()]), // This should cause 0 results
        services: None,
        states: None,
        environment: None,
        application: None,
        synced_after: None,
        limit: Some(10),
        score_threshold: Some(0.05),
        include_metadata: true,
        use_anonymous_ids: false,
    };
    
    println!("\n🔍 Testing estate search WITH region filter...");
    let filtered_results = estate_rag.search_service
        .search_estate_resources("AWS EC2 instances", filtered_search_options, None)
        .await?;
    
    println!("✅ Estate Search Results (With Region Filter): {}", filtered_results.len());
    
    // Summary
    println!("\n🎯 ANALYSIS:");
    println!("   - Without filters: {} results", results.len());
    println!("   - With region filter: {} results", filtered_results.len());
    
    if results.len() > 0 && filtered_results.len() == 0 {
        println!("   ❌ CONFIRMED: Metadata filters are causing 0 results");
        println!("   🔐 CAUSE: Document metadata is encrypted, filters can't match plaintext fields");
    }
    
    Ok(())
}