/*
 * Copyright (c) 2026 University of Insubria <https://www.uninsubria.it>
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version. All we ask is that proper credit is given
 * for our work, which includes - but is not limited to - adding the above
 * copyright notice to the beginning of your source code files, and to any
 * copyright notice that you may distribute with programs based on this work.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.
 * <https://fsf.org/>
 */

package qsardes.descriptor;

import Jama.Matrix;
import java.util.Arrays;
import java.util.HashMap;
import qsardes.molecule.Molecule;
import qsardes.molecule.AbstractMoleculeBuilder;
import qsardes.util.UtilsCalc;
import qsardes.util.UtilsConv;
import java.util.List;
import java.util.Map;
import org.openscience.cdk.graph.matrix.AdjacencyMatrix;

/**
 * Adjacency distance matrix descriptors abstract class.
 *
 * @author Nicola Chirico
 */
public abstract class DescriptorAdjacencyMatrix implements Descriptor
{
    protected DescriptorAdjacencyMatrix()
    {
    }

    @Override
    public String toString()
    {
        return "Adjacency matrix";
    }

    @Override
    public DescriptorType get_descriptor_type()
    {
        return DescriptorType.valueOf("DESCRIPTOR");
    }

    @Override
    public List<String> get_descriptor_names()
    {
        return Arrays.asList(
                "SpMax_A", "SpDiam_A", "SpAD_A", "SpMAD_A",
                "EE_A",    "VE1_A",    "VE2_A",  "VE3_A",
                "VR1_A",   "VR2_A",    "VR3_A");
    }

    @Override
    public Map<String, String> get_descriptor_values(
            AbstractMoleculeBuilder mol_build)
    {
        prepare_descr_map();

        try {
            mol = new Molecule(mol_build);
            calculate_descr();
        } catch (Exception ex) {
            System.err.println(ex);
        }

        return descr_map;
    }

    private void prepare_descr_map()
    {
        final String NAN = String.valueOf(Double.NaN);

        get_descriptor_names().forEach(name -> descr_map.put(name, NAN));
    }

    private void calculate_descr()
    {
        var topo_matr = AdjacencyMatrix.getMatrix​(mol.get_atom_container());

        var eig_decomp = new Matrix(new UtilsConv().convert_to_double(
                topo_matr)).eig();

        double[] eig_values = eig_decomp.getRealEigenvalues();
        double[][] eig_vec_array = eig_decomp.getV().getArray();

        var utils_calc = new UtilsCalc();

        double eig_val_min = utils_calc.get_min(eig_values);
        double eig_val_max = utils_calc.get_max(eig_values);

        double sp_ad_sum = utils_calc.calc_ad_sum(eig_values);
        double sp_ve1_sum = utils_calc.calc_col_abs_sum(eig_vec_array,
                eig_vec_array[0].length - 1);

        double ee_lse_exp_sum = utils_calc.calc_ee_lse_exp_sum(eig_values);

        double vr1_sum = utils_calc.calc_vr1_sum(mol.get_atom_container(),
                eig_vec_array, eig_vec_array[0].length - 1);

        descr_map.put("SpMax_A", String.valueOf(eig_val_max));

        descr_map.put("SpDiam_A",
                String.valueOf(eig_val_max - eig_val_min));

        descr_map.put("SpAD_A", String.valueOf(sp_ad_sum));

        descr_map.put("SpMAD_A", String.valueOf(sp_ad_sum / eig_values.length));

        // log(1 + b) -> log(a + b) = log(exp(log(a)) + exp(log(b)))
        // eig_val_max reassembles the final part of the Log-Sum-Exp func.
        descr_map.put("EE_A", String.valueOf(
                StrictMath.log(StrictMath.exp(StrictMath.log(1.0))
                        + StrictMath.exp(eig_val_max
                                + StrictMath.log(ee_lse_exp_sum)))));

        descr_map.put("VE1_A",
                String.valueOf(Math.abs(sp_ve1_sum)));

        descr_map.put("VE2_A", String.valueOf(
                Math.abs(sp_ve1_sum) / (double) eig_values.length));

        descr_map.put("VE3_A", String.valueOf(
                StrictMath.log(((double) eig_values.length / 10.0)
                    * sp_ve1_sum)));

        descr_map.put("VR1_A", String.valueOf(vr1_sum));

        descr_map.put("VR2_A", String.valueOf(
                vr1_sum / (double) eig_values.length));

        descr_map.put("VR3_A", String.valueOf(
                StrictMath.log(((double) eig_values.length / 10.0)
                * vr1_sum)));
    }

    private final Map<String, String> descr_map = new HashMap<>();

    private Molecule mol;
}
