//! Debug script to manually test decryption of failing documents

use anyhow::Result;
use rag_module::*;

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔍 DEBUGGING DECRYPTION PROCESS");
    println!("===============================\n");
    
    let rag = create_rag_module("./test_data").await?;
    rag.initialize().await?;
    
    // Try to manually get a document and see its raw structure
    let doc_result = rag.vector_store.get_document("aws_estate", "4283e6b6-b086-4ea9-9c77-a12351a8f4a3").await?;
    
    if let Some(doc) = doc_result {
        println!("📋 RAW DOCUMENT STRUCTURE:");
        println!("   ID: {}", doc.id);
        println!("   Content length: {}", doc.content.len());
        println!("   Metadata keys: {:?}", doc.metadata.keys().collect::<Vec<_>>());
        
        // Check if we have encrypted metadata
        if let Some(encrypted_metadata) = doc.metadata.get("_encrypted_metadata") {
            println!("\n🔐 ENCRYPTED METADATA FOUND:");
            println!("   Type: {:?}", encrypted_metadata);
            
            if let Some(encrypted_str) = encrypted_metadata.as_str() {
                println!("   Encrypted string length: {}", encrypted_str.len());
                println!("   First 100 chars: {}", &encrypted_str[..std::cmp::min(100, encrypted_str.len())]);
                
                // Try to decrypt it manually
                if let Some(encryption_service) = &rag.search_service.encryption_service {
                    println!("\n🔓 ATTEMPTING DECRYPTION:");
                    match encryption_service.decrypt_content(encrypted_str).await {
                        Ok(decrypted) => {
                            println!("   ✅ Decryption successful!");
                            println!("   Decrypted length: {}", decrypted.len());
                            println!("   Decrypted content: {}", decrypted);
                        },
                        Err(e) => {
                            println!("   ❌ Decryption failed: {}", e);
                        }
                    }
                } else {
                    println!("   ❌ No encryption service available");
                }
            } else {
                println!("   ❌ Encrypted metadata is not a string");
            }
        } else {
            println!("\n❌ NO ENCRYPTED METADATA FOUND");
        }
    } else {
        println!("❌ Document not found!");
    }
    
    Ok(())
}