// RLX — versatile ML compiler + runtime.
// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.

//! Numerical-parity test for se_t descriptor.

use std::collections::HashMap;
use std::path::Path;

use deepmd::descriptor_se_t::{build_se_t_descriptor, SeTConfig};
use rlx_ir::{DType, Graph, Shape};
use rlx_runtime::{Device, Session};
use serde::Deserialize;

#[derive(Deserialize)]
struct Tensor {
    name: String,
    #[allow(dead_code)]
    shape: Vec<usize>,
    data: Vec<f32>,
}

#[derive(Deserialize)]
struct Config {
    rcut: f64,
    rcut_smth: f64,
    sel: Vec<usize>,
    neuron: Vec<usize>,
    resnet_dt: bool,
    activation_function: String,
    nf: usize,
    nloc: usize,
}

#[derive(Deserialize)]
struct Fixture {
    config: Config,
    params: HashMap<String, Tensor>,
    inputs: Vec<Tensor>,
    outputs: Vec<Tensor>,
}

fn find_named<'a>(list: &'a [Tensor], name: &str) -> &'a Tensor {
    list.iter().find(|t| t.name == name).expect("missing tensor")
}

fn assert_allclose(actual: &[f32], expected: &[f32], atol: f32, rtol: f32, label: &str) {
    assert_eq!(actual.len(), expected.len());
    let mut max_abs = 0f32;
    for (i, (a, b)) in actual.iter().zip(expected.iter()).enumerate() {
        let abs = (a - b).abs();
        let tol = atol + rtol * b.abs();
        max_abs = max_abs.max(abs);
        assert!(abs <= tol, "{label}[{i}]: actual={a:.6e} expected={b:.6e} |Δ|={abs:.3e}");
    }
    eprintln!("{label}: max_abs={max_abs:.3e}");
}

#[allow(dead_code)]
fn i32_bytes_to_f32s(bytes: &[u8]) -> Vec<f32> {
    bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect()
}

#[test]
fn se_t_matches_python_reference() {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent().unwrap().parent().unwrap()
        .join("tests/fixtures/se_t_small.json");
    let fx: Fixture = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();

    let cfg = SeTConfig {
        rcut: fx.config.rcut,
        rcut_smth: fx.config.rcut_smth,
        sel: fx.config.sel.clone(),
        neuron: fx.config.neuron.clone(),
        resnet_dt: fx.config.resnet_dt,
        activation_function: fx.config.activation_function.clone(),
        type_map: None,
    };
    let nf = fx.config.nf;
    let nloc = fx.config.nloc;
    let nnei: usize = cfg.sel.iter().sum();

    let mut g = Graph::new("se_t_parity");
    let env_mat = g.input("env_mat", Shape::new(&[nf, nloc, nnei, 4], DType::F32));
    let atype = g.input("atype", Shape::new(&[nf, nloc], DType::I32));
    let out = build_se_t_descriptor(&mut g, &cfg, env_mat, atype, nf, nloc, None).expect("build");
    g.set_outputs(vec![out.descriptor]);

    let session = Session::new(Device::Cpu);
    let mut compiled = session.compile(g);
    for (name, t) in &fx.params {
        let bytes: Vec<u8> = t.data.iter().flat_map(|v| v.to_le_bytes()).collect();
        compiled.set_param_typed(name, &bytes, DType::F32);
    }

    let em_raw = find_named(&fx.inputs, "env_mat_raw");
    let atype_ext = find_named(&fx.inputs, "atype_ext");
    let atype_loc_f32: Vec<f32> = atype_ext.data.iter().take(nf * nloc).copied().collect();

    let outputs = compiled.run(&[
        ("env_mat", em_raw.data.as_slice()),
        ("atype", atype_loc_f32.as_slice()),
    ]);
    let expected = find_named(&fx.outputs, "descriptor");
    assert_allclose(&outputs[0], &expected.data, 1e-4, 1e-4, "descriptor");
}
