use cannon_core::ReconciliationEngine;
use cannon_core::types::{NormalizedEntity, Decision};
use cannon_core::overrides::OverrideResolver;
use metrics_exporter_prometheus::PrometheusBuilder;
use uuid::Uuid;
use std::collections::HashMap;

#[test]
fn test_metrics_emission() {
    // 1. Install Prometheus recorder
    let handle = PrometheusBuilder::new()
        .install_recorder()
        .expect("failed to install recorder");

    // 2. Setup engine
    let engine = ReconciliationEngine::new(
        vec![Box::new(cannon_core::matching::ExactMatch {
            field: "email".to_string(),
            weight: 1.0,
            case_insensitive: true,
            normalize: true,
            normalizer: None,
            rule_name: "email_exact".to_string(),
        })],
        vec![Box::new(cannon_core::blocking::FieldBlocking { fields: vec!["email".to_string()] })],
        0.8,
        0.6,
    );

    // 3. Create entities that match
    let e1 = NormalizedEntity {
        id: Uuid::new_v4(),
        tenant_id: Uuid::new_v4(),
        external_id: "e1".to_string(),
        entity_type: "customer".to_string(),
        data: HashMap::from([("email".to_string(), "test@example.com".to_string())]),
        source_name: "test".to_string(),
        valid_from: None,
        valid_to: None,
        last_updated: chrono::Utc::now(),
    };
    let e2 = NormalizedEntity {
        id: Uuid::new_v4(),
        tenant_id: e1.tenant_id,
        external_id: "e2".to_string(),
        entity_type: "customer".to_string(),
        data: HashMap::from([("email".to_string(), "test@example.com".to_string())]),
        source_name: "test".to_string(),
        valid_from: None,
        valid_to: None,
        last_updated: chrono::Utc::now(),
    };

    let resolver = OverrideResolver::new(vec![]);
    
    // 4. Run reconciliation
    let decisions = engine.reconcile(&[e1, e2], &resolver);
    assert_eq!(decisions.len(), 1);
    assert_eq!(decisions[0].decision, Decision::Merge);

    // 5. Verify metrics
    let output = handle.render();
    println!("Metrics output:\n{}", output);

    assert!(output.contains("reconcile_duration_seconds{quantile=\"1\"}"));
    assert!(output.contains("match_decisions_total{decision=\"Merge\"} 1"));
}
