// Parity test for se_atten_v2 (strip mode, smooth=True, dotr=True).

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

use deepmd::descriptor_dpa1::DPA1Inputs;
use deepmd::descriptor_se_atten_v2::{build_se_atten_v2_descriptor, SeAttenV2Config};
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>, ntypes: usize,
    neuron: Vec<usize>, axis_neuron: usize, tebd_dim: usize,
    resnet_dt: bool, type_one_side: bool,
    attn: usize, attn_layer: usize, attn_dotr: bool,
    num_heads: usize, normalize: bool, scaling_factor: f32,
    ln_eps: f32, activation_function: String, concat_output_tebd: bool,
    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}");
}

fn run_se_atten_v2_fixture(fixture_name: &str) {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent().unwrap().parent().unwrap()
        .join("tests/fixtures").join(fixture_name);
    let fx: Fixture = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();

    let cfg = SeAttenV2Config {
        rcut: fx.config.rcut,
        rcut_smth: fx.config.rcut_smth,
        sel: fx.config.sel.clone(),
        ntypes: fx.config.ntypes,
        neuron: fx.config.neuron.clone(),
        axis_neuron: fx.config.axis_neuron,
        tebd_dim: fx.config.tebd_dim,
        resnet_dt: fx.config.resnet_dt,
        attn: fx.config.attn,
        attn_layer: fx.config.attn_layer,
        attn_dotr: fx.config.attn_dotr,
        num_heads: fx.config.num_heads,
        normalize: fx.config.normalize,
        scaling_factor: fx.config.scaling_factor,
        ln_eps: fx.config.ln_eps,
        type_one_side: fx.config.type_one_side,
        activation_function: fx.config.activation_function.clone(),
        concat_output_tebd: fx.config.concat_output_tebd,
    };
    let nf = fx.config.nf;
    let nloc = fx.config.nloc;
    let nnei: usize = cfg.sel.iter().sum();

    let mut g = Graph::new("se_atten_v2_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 nei_atype = g.input("nei_atype", Shape::new(&[nf, nloc, nnei], DType::I32));
    let nlist_mask = g.input("nlist_mask", Shape::new(&[nf, nloc, nnei], DType::F32));
    let sw = g.input("sw", Shape::new(&[nf, nloc, nnei], DType::F32));
    let t_table = g.input(
        "type_embed_in",
        Shape::new(&[cfg.ntypes + 1, cfg.tebd_dim], DType::F32),
    );
    let out = build_se_atten_v2_descriptor(
        &mut g, &cfg,
        DPA1Inputs {
            env_mat_raw: env_mat, atype_loc: atype, nei_atype,
            nlist_mask, sw, type_embedding: t_table,
        },
        nf, nloc,
    ).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 nei_atype_in = find_named(&fx.inputs, "nei_atype");
    let nlist_mask_in = find_named(&fx.inputs, "nlist_mask");
    let sw_in = find_named(&fx.inputs, "sw");
    let tab_in = find_named(&fx.inputs, "type_embedding");
    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()),
        ("nei_atype", nei_atype_in.data.as_slice()),
        ("nlist_mask", nlist_mask_in.data.as_slice()),
        ("sw", sw_in.data.as_slice()),
        ("type_embed_in", tab_in.data.as_slice()),
    ]);
    let expected = find_named(&fx.outputs, "descriptor");
    assert_allclose(&outputs[0], &expected.data, 1e-5, 1e-4, "descriptor");
}

#[test]
fn se_atten_v2_matches_python_reference() {
    run_se_atten_v2_fixture("se_atten_v2_small.json");
}

#[test]
fn se_atten_v2_nf2_matches_python_reference() {
    run_se_atten_v2_fixture("se_atten_v2_nf2.json");
}
