//! Debug Decrypt - Examine actual encrypted document content and metadata

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

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔓 DECRYPT DEBUG - Examining Actual Stored Data");
    println!("==============================================\n");
    
    let rag = create_rag_module("./test_data").await?;
    rag.initialize().await?;
    
    let user_id = "344804c8-50b1-703a-7baa-5f9f498598f8";
    
    // Get all documents to see their raw structure
    let docs = rag.get_collection_documents("aws_estate", user_id).await?;
    
    println!("📊 Total documents: {}\n", docs.len());
    
    // Take first 3 documents and examine them in detail
    for (i, doc) in docs.iter().take(30).enumerate() {
        println!("🔍 DOCUMENT {} ANALYSIS:", i + 1);
        println!("  ID: {}", doc.id);
        println!("  Content length: {} chars", doc.content.len());
        println!("  Content preview: {}", doc.content.chars().take(100).collect::<String>());
        
        println!("  📋 METADATA STRUCTURE:");
        println!("    encrypted_metadata: {} chars", doc.metadata.encrypted_metadata.len());
        println!("    encrypted_content: {}", doc.metadata.encrypted_content);
        println!("    created_at: {}", doc.metadata.created_at);
        println!("    updated_at: {}", doc.metadata.updated_at);
        
        // Try to decrypt the metadata
        println!("  🔓 ATTEMPTING TO DECRYPT METADATA:");
        let enc_service = &rag.encryption_service;
        match enc_service.decrypt_content(&doc.metadata.encrypted_metadata).await {
            Ok(decrypted) => {
                println!("    ✅ Successfully decrypted:");
                println!("    {}", decrypted);
                
                // Try to parse as JSON
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&decrypted) {
                    println!("    📋 DECRYPTED JSON FIELDS:");
                    if let Some(obj) = json.as_object() {
                        for (key, value) in obj {
                            println!("      {}: {}", key, value);
                        }
                    }
                }
            },
            Err(e) => println!("    ❌ Decryption failed: {}", e)
        }
        
        // Try to decrypt the content too
        println!("  🔓 ATTEMPTING TO DECRYPT CONTENT:");
        match enc_service.decrypt_content(&doc.content).await {
            Ok(decrypted_content) => {
                println!("    ✅ Successfully decrypted content:");
                println!("    {}", decrypted_content.chars().take(3000).collect::<String>()); // Show first 200 chars
            },
            Err(e) => println!("    ❌ Content decryption failed: {}", e)
        }
        
        println!("  {}\n", "=".repeat(80));
    }
    
    Ok(())
}