/*
 * 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.TopologicalMatrix;
import org.openscience.cdk.interfaces.IAtomContainer;

/**
 * Topological distance matrix descriptor abstract class.
 *
 * @author Nicola Chirico
 */
public abstract class DescriptorTopologicalDistance implements Descriptor
{
    protected DescriptorTopologicalDistance()
    {
    }

    @Override
    public String toString()
    {
        return "Topological distance";
    }

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

    @Override
    public List<String> get_descriptor_names()
    {
        return Arrays.asList(
                "SpMax_D", "SpDiam_D", "SpAD_D", "SpMAD_D", "EE_D",
                "VE1_D",   "VE2_D",    "VE3_D",  "VR1_D",   "VR2_D",
                "VR3_D");
    }

    @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;
    }

    protected abstract double calculate_sp_ve1_sum(UtilsCalc utils_calc,
            double[][] eig_vec_array);

    protected abstract double calculate_sp_vr1_sum(IAtomContainer iac,
            UtilsCalc utils_calc, double[][] eig_vec_array);

    protected abstract double get_sp_ve1_sum(double sp_ve1_sum);

    protected abstract double get_ve3(double sp_ve1_sum, int atom_count);

    protected abstract double get_vr3(double vr1_sum, int atom_count);

    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()
    {
        final int ATOM_COUNT = mol.get_atom_container().getAtomCount();

        var topo_matr = TopologicalMatrix.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 = calculate_sp_ve1_sum(utils_calc, eig_vec_array);

        double ee_lse_exp_sum = utils_calc.calc_ee_lse_exp_sum(eig_values);

        double vr1_sum = calculate_sp_vr1_sum(mol.get_atom_container(),
                utils_calc, eig_vec_array);

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

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

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

        descr_map.put("SpMAD_D", String.valueOf(sp_ad_sum / ATOM_COUNT));

        // 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.
        try {
            descr_map.put("EE_D", String.valueOf(
                    StrictMath.log(StrictMath.exp(StrictMath.log(1.0))
                            + StrictMath.exp(eig_val_max
                                    + StrictMath.log(ee_lse_exp_sum)))));
        } catch (Exception ex) {
            descr_map.put("EE_D", String.valueOf(Double.NaN));
        }

        descr_map.put("VE1_D", String.valueOf(get_sp_ve1_sum(sp_ve1_sum)));

        descr_map.put("VE2_D", String.valueOf(
                    get_sp_ve1_sum(sp_ve1_sum) / (double) ATOM_COUNT));

        descr_map.put("VE3_D", String.valueOf(get_ve3(sp_ve1_sum, ATOM_COUNT)));

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

        descr_map.put("VR2_D", String.valueOf(vr1_sum / (double) ATOM_COUNT));

        descr_map.put("VR3_D", String.valueOf(get_vr3(vr1_sum, ATOM_COUNT)));
    }

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

    private Molecule mol;
}
