use anyhow::Result;
use atlas::vault_store;
use vault::retrieval::query::VaultQuery;

pub fn handle(query: String, top_k: usize) -> Result<()> {
    let q = VaultQuery::new(&query).top_k(top_k);
    let vault = vault_store::vault().lock().unwrap();
    let facts = vault.query(&q);

    if facts.is_empty() {
        println!("No vault facts found for \"{query}\".");
        return Ok(());
    }

    println!("bctx recall: \"{query}\" — {} result(s)\n", facts.len());
    for f in &facts {
        println!(
            "  [{tier}] {cat}/{key}  (confidence: {conf:.0}%)",
            tier = tier_label(&f.tier),
            cat = f.category,
            key = f.key,
            conf = f.confidence * 100.0,
        );
        println!("    {}", f.value);
        if !f.tags.is_empty() {
            println!("    tags: {}", f.tags.join(", "));
        }
        println!();
    }
    Ok(())
}

fn tier_label(tier: &vault::fact::MemoryTier) -> &'static str {
    match tier {
        vault::fact::MemoryTier::Immediate => "immediate",
        vault::fact::MemoryTier::Resonant => "resonant",
        vault::fact::MemoryTier::Crystallized => "crystallized",
        vault::fact::MemoryTier::Dormant => "dormant",
        vault::fact::MemoryTier::Phantom => "phantom",
    }
}
