//! Integration test: real embedding pipeline end-to-end.
//!
//! Run with:
//!   cargo test -p mimirs-agent --test real_embedding_e2e -- --ignored
//!
//! Environment variables:
//!   MIMIRS_MODEL_PATH — path to LFM2.5-VL-450M GGUF or BERT safetensors

use std::sync::Arc;

use mimirs_agent::{AgentConfig, MimirAgent};
use mimirs_core::{MemoryAgent, MemoryInput};
use mimirs_store::Urdarbrunnr;

fn block_on<F: std::future::Future>(f: F) -> F::Output {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(f)
}

fn create_agent(model_path: &str) -> (MimirAgent, tempfile::TempDir) {
    let dir = tempfile::tempdir().unwrap();
    let well = Arc::new(Urdarbrunnr::opna(dir.path(), 384).unwrap());
    let config = AgentConfig {
        agent_id: "test-agent".into(),
        backend: "urdarbrunnr".into(),
        ha_enabled: false,
        session_id: Some("test-session".into()),
        model_path: model_path.into(),
        contradiction_threshold: 0.8,
        coherence_threshold: 0.3,
        decay_rate: 1e-5,
        target_metastability: 0.8,
        use_local_encoder: true,
        manifold_dim: 384,
    };
    let agent = MimirAgent::new(well, config);
    (agent, dir)
}

fn store_text(agent: &MimirAgent, text: &str) -> mimirs_core::MemoryId {
    let input = MemoryInput {
        content: text.to_string(),
        metadata: None,
        verifiability: None,
        scope: Some(mimirs_core::MemoryScope::Session),
        memory_class: None,
        source_session: None,
    };
    block_on(agent.store(input)).expect("store failed")
}

#[test]
fn test_dummy_embedding_always_available() {
    let (agent, _dir) = create_agent("/nonexistent/model.gguf");

    assert!(!agent.has_real_embedding());
    assert_eq!(agent.embedding_backend(), "dummy");

    // Should still produce valid embeddings (hash-based)
    let id = store_text(&agent, "test content");
    assert!(!id.to_string().is_empty());
}

#[test]
#[ignore = "requires model file at MIMIRS_MODEL_PATH or ../models/sleipnir.gguf"]
fn test_real_embedding_backend_selection() {
    // Try multiple locations for the model file
    let candidates = [
        std::env::var("MIMIRS_MODEL_PATH").ok(),
        Some("./models/sleipnir.gguf".to_string()),
        Some("../models/sleipnir.gguf".to_string()),
        Some(concat!(env!("CARGO_MANIFEST_DIR"), "/../models/sleipnir.gguf").to_string()),
    ];

    let model_path = candidates
        .into_iter()
        .flatten()
        .find(|p| std::path::Path::new(p).exists());

    let model_path = match model_path {
        Some(p) => p,
        None => {
            eprintln!("SKIP: model file not found");
            return;
        }
    };

    let (agent, _dir) = create_agent(&model_path);

    assert!(
        agent.has_real_embedding(),
        "Expected real embedding backend, got: {}",
        agent.embedding_backend()
    );

    // Store text and verify source_session tagging
    let python_id = store_text(&agent, "Python is a dynamically typed programming language");
    let mem = block_on(agent.get_memory(python_id)).expect("get_memory failed");
    assert_eq!(mem.source_session, Some("test-session".into()));
}
