use anyhow::Result;
use rag_module::RagModule;
use rag_module::types::Document;
use serde_json::json;
use indexmap::IndexMap;

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔧 Debug: Document Creation Test");
    
    // Initialize RAG module
    let mut rag_module = RagModule::new("./debug-test-data").await?;
    rag_module.initialize().await?;
    
    // Set user context for document operations
    let user_id = "test_user_debug";
    rag_module.set_user_context(user_id).await?;
    
    println!("✅ RAG Module initialized with user context: {}", user_id);

    // Create a simple test document
    let mut metadata = IndexMap::new();
    metadata.insert("resource_type".to_string(), json!("ec2-instance"));
    metadata.insert("account_id".to_string(), json!("123456789012"));
    metadata.insert("region".to_string(), json!("us-east-1"));
    metadata.insert("service".to_string(), json!("ec2"));
    metadata.insert("state".to_string(), json!("running"));
    metadata.insert("collection_type".to_string(), json!("aws_estate"));
    
    let test_doc = Document::new(
        "arn:aws:ec2:us-east-1:123456789012:instance/i-test123".to_string(), 
        "Test EC2 Instance in us-east-1 - State: running".to_string()
    ).with_metadata(metadata);
    
    println!("🔍 Test document created:");
    println!("   ID: {}", test_doc.id);
    println!("   Content: {}", test_doc.content);
    println!("   Metadata keys: {:?}", test_doc.metadata.keys().collect::<Vec<_>>());
    
    // Test direct document service call
    println!("\n🧪 Testing direct document service call...");
    match rag_module.document_service.add_document("aws_estate", test_doc.clone()).await {
        Ok(doc_id) => println!("✅ Direct document service call succeeded: {}", doc_id),
        Err(e) => {
            println!("❌ Direct document service call failed: {}", e);
            println!("Error details: {:?}", e);
        }
    }
    
    // Test via RagModule create method
    println!("\n🧪 Testing RagModule create method...");
    match rag_module.create(vec![test_doc]).await {
        Ok(result) => {
            println!("✅ RagModule create succeeded:");
            println!("   Created: {}", result.created);
            println!("   Failed: {:?}", result.failed);
        },
        Err(e) => {
            println!("❌ RagModule create failed: {}", e);
            println!("Error details: {:?}", e);
        }
    }
    
    // Check collection health
    println!("\n📊 Collection health:");
    let collections_health = rag_module.collection_manager.get_collections_health().await?;
    println!("   Estate Collection: {} points", collections_health.aws_estate.points_count);
    
    Ok(())
}