use edifact_mapper::{DataDir, Mapper, MapperError};

fn skip_if_no_bundles() -> Option<Mapper> {
    let bundle_dir = std::path::Path::new("/tmp/edifact-bundles");
    if !bundle_dir.join("edifact-data-FV2504.bin").exists() {
        eprintln!("Skipping: run `cargo run -p automapper-generator -- bundle-data --output-dir /tmp/edifact-bundles` first");
        return None;
    }
    match Mapper::from_data_dir(DataDir::path(bundle_dir).eager(&["FV2504"])) {
        Ok(m) => Some(m),
        Err(e) => {
            eprintln!("Skipping: bundle load failed (possibly incompatible version): {e}");
            None
        }
    }
}

#[test]
fn test_mapper_lists_variants() {
    let Some(mapper) = skip_if_no_bundles() else {
        return;
    };
    let variants = mapper.variants("FV2504").unwrap();
    assert!(
        variants.len() >= 16,
        "Expected 16+ variants, got {}",
        variants.len()
    );
    assert!(variants.contains(&"UTILMD_Strom".to_string()));
    assert!(variants.contains(&"MSCONS".to_string()));
    assert!(variants.contains(&"APERAK".to_string()));
    assert!(variants.contains(&"CONTRL".to_string()));
}

#[test]
fn test_mapper_engine_for_pid() {
    let Some(mapper) = skip_if_no_bundles() else {
        return;
    };
    let engine = mapper.engine("FV2504", "UTILMD_Strom", "55001").unwrap();
    assert!(
        engine.definitions().len() > 10,
        "PID 55001 should have many definitions"
    );
}

#[test]
fn test_mapper_conversion_service() {
    let Some(mapper) = skip_if_no_bundles() else {
        return;
    };
    let _service = mapper.conversion_service("FV2504", "UTILMD_Strom").unwrap();
}

#[test]
fn test_mapper_nonexistent_pid() {
    let Some(mapper) = skip_if_no_bundles() else {
        return;
    };
    match mapper.engine("FV2504", "UTILMD_Strom", "99999") {
        Err(MapperError::PidNotFound { .. }) => {}
        Err(e) => panic!("Expected PidNotFound, got: {e}"),
        Ok(_) => panic!("Expected error, got Ok"),
    }
}

#[test]
fn test_mapper_nonexistent_variant() {
    let Some(mapper) = skip_if_no_bundles() else {
        return;
    };
    match mapper.conversion_service("FV2504", "NONEXISTENT") {
        Err(MapperError::VariantNotFound { .. }) => {}
        Err(e) => panic!("Expected VariantNotFound, got: {e}"),
        Ok(_) => panic!("Expected error, got Ok"),
    }
}
