use mimirs_agent::MimirAgent;
use mimirs_core::{
    MemoryAgent, MemoryClass, MemoryInput, MemoryScope, RecallQuery, VerifiabilityStage,
};
use mimirs_store::Urdarbrunnr;
use std::sync::Arc;
use tempfile::tempdir;

#[tokio::test]
async fn test_comprehensive_memory_lifecycle() {
    // 1. Setup - Product Team / Senior Engineer criteria
    let dir = tempdir().unwrap();
    let well = Arc::new(Urdarbrunnr::opna(dir.path(), 384).unwrap());
    let agent = MimirAgent::new(well, mimirs_agent::AgentConfig::default());

    // 2. Store - PM Acceptance Criteria
    let input = MemoryInput {
        content: "The spectral radius of a reservoir should be less than 1.0 for the echo state property.".to_string(),
        metadata: None,
        verifiability: Some(VerifiabilityStage::Speculative),
        scope: Some(MemoryScope::Agent),
        memory_class: Some(MemoryClass::Semantic),
        source_session: None,
    };

    let id = agent.store(input).await.expect("Should store memory");
    assert!(!id.to_string().is_empty());

    // 3. Recall - Junior Developer criteria
    let query = RecallQuery::new("spectral radius").with_limit(1);
    let results = agent.recall(query).await.expect("Should recall memory");

    // We expect at least one result (the one we just stored)
    // Note: The density matrix measurement might return multiple results if there's overlap
    assert!(!results.is_empty());

    // 4. Consolidation Smoke Test - QA Engineer criteria
    let report = agent.consolidate().await.expect("Should run consolidation");
    assert!(report.memories_processed >= 1);
    // duration_ms is always >= 0 (u64); just verify consolidation ran
    assert!(report.memories_processed > 0 || report.duration_ms == 0);

    // 5. Snapshot - DevOps Engineer criteria
    let snapshot = agent.snapshot().await.expect("Should create snapshot");
    assert!(!snapshot.memories.is_empty());
    assert!(snapshot.identity.is_some());
    assert!(!snapshot.timestamp.is_empty());

    // 6. Identity Manifold - Security Engineer criteria
    // Verify identity is persistent and scoped
    let identity = snapshot.identity.unwrap();
    assert!(identity.beliefs.is_empty()); // Initial state
}

#[tokio::test]
async fn test_cross_crate_pipeline() {
    let dir = tempdir().unwrap();
    let well = Arc::new(Urdarbrunnr::opna(dir.path(), 384).unwrap());
    let agent = MimirAgent::new(well, mimirs_agent::AgentConfig::default());

    // Store multiple memories to test flow
    for i in 0..5 {
        let input = MemoryInput {
            content: format!("Knowledge atom {}", i),
            metadata: None,
            verifiability: None,
            scope: None,
            memory_class: Some(MemoryClass::Episodic),
            source_session: None,
        };
        agent.store(input).await.unwrap();
    }

    // Verify retrieval across the pipeline
    let results = agent.recall(RecallQuery::new("Knowledge")).await.unwrap();
    assert!(!results.is_empty());
}
