use anyhow::Result;
use rag_module::RagModule;

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔍 Testing AWS Estate Decryption\n");
    
    let user_id = "cudewvsbxakj1n";
    
    // Initialize RAG module
    let rag_module = RagModule::new("./test_data").await?;
    rag_module.initialize().await?;
    
    println!("🔓 Decrypting AWS Estate documents for user: {}\n", user_id);
    
    // Get encrypted documents
    let encrypted_docs = rag_module.get_collection_documents("aws_estate", user_id).await?;
    
    println!("📊 Found {} encrypted estate documents\n", encrypted_docs.len());
    
    // Decrypt each document
    for (idx, doc) in encrypted_docs.iter().enumerate() {
        println!("📄 Document {} (ID: {})", idx + 1, doc.id);
        println!("   Created: {}", doc.metadata.created_at);
        
        // Decrypt content
        match rag_module.encryption_service.decrypt_content(&doc.content).await {
            Ok(decrypted_content) => {
                // Parse as JSON for pretty display
                match serde_json::from_str::<serde_json::Value>(&decrypted_content) {
                    Ok(content_json) => {
                        println!("   📦 Decrypted Content:");
                        println!("{}\n", serde_json::to_string_pretty(&content_json)?);
                    }
                    Err(_) => {
                        println!("   📦 Decrypted Content (raw):\n   {}\n", decrypted_content);
                    }
                }
            }
            Err(e) => {
                println!("   ❌ Failed to decrypt content: {}\n", e);
            }
        }
        
        // Decrypt metadata
        let metadata_json = serde_json::json!({"_encrypted_metadata": doc.metadata.encrypted_metadata.clone()});
        match rag_module.encryption_service.decrypt_metadata(&metadata_json).await {
            Ok(decrypted_metadata) => {
                println!("   🏷️  Decrypted Metadata:");
                println!("{}\n", serde_json::to_string_pretty(&decrypted_metadata)?);
            }
            Err(e) => {
                println!("   ❌ Failed to decrypt metadata: {}\n", e);
            }
        }
        
        println!("   ─────────────────────────────────────────────────────\n");
    }
    
    println!("✅ Decryption complete!");
    
    Ok(())
}
