/* BEGIN software license
 *
 * MsXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright 2009--2026 by Filippo Rusconi
 *
 * http://www.msxpertsuite.org
 *
 * This file is part of the MsXpertSuite project.
 *
 * The MsXpertSuite project is the successor of the massXpert project. This
 * project now includes various independent modules:
 *
 * - massXpert, model polymer chemistries and simulate mass spectrometric data;
 * - mineXpert, a powerful TIC chromatogram/mass spectrum viewer/miner;
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * END software license
 */


#pragma once


/////////////////////// Qt includes


/////////////////////// pappsomspp includes
#include <pappsomspp/core/trace/trace.h>


/////////////////////// Local includes
#include "MsXpS/export-import-config.h"
#include "MsXpS/libXpertMassCore/globals.hpp"
#include "MsXpS/libXpertMassCore/Processing/HighResPeakPicker.hpp"

namespace MsXpS
{
namespace libXpertMassCore
{


class DECLSPEC IsotopicCluster: public QObject
{
  Q_OBJECT

  public:
  struct DECLSPEC ChargeValidationResults
  {
    int centroidCount       = 0;
    double mzSpacingsMean   = 0.0;
    double mzSpacingsStdDev = 0.0;
    double mzSpacingsMin    = 0.0;
    double mzSpacingsMax    = 0.0;
    double mzSpacingsMedian = 0.0;

    // --- Candidate as inverse of mzSpacingsMedian ---
    int putativeCharge = 0;

    // --- Statistical Validation ---
    bool validStatistics   = false;
    double r2              = 0.0;
    double stdErrorOfSlope = 0.0; // Standard Error of the slope
    double chargeConfidenceIntervalLower =
      0.0; // 95% Confidence Interval Lower Bound
    double chargeConfidenceIntervalUpper =
      0.0; // 95% Confidence Interval Upper Bound
    double pairwiseCoefficientOfVariation =
      0.0; // Coefficient of Variation (for n <= 3)

    // --- Physical Validation ---
    bool physicallyValid = false;
    double ppmRMSE       = 0.0;

    // --- User-Configurable Tolerances ---
    double maxPpmRMSE    = 5.0; // e.g., 3.0 for Orbitrap, 10.0 for Q-TOF
    double minR2         = 0.98;
    double maxPairwiseCV = 0.02; // 2%

    // --- Final Decision ---
    enum class Verdict
    {
      HIGH_CONF_ACCEPT,
      LOW_CONF_ACCEPT,
      REJECT_NOISE_COMB,
      REJECT_PURE_NOISE,
      AMBIGUOUS
    };

    Verdict verdict = Verdict::AMBIGUOUS;

    ChargeValidationResults();

    ChargeValidationResults(const ChargeValidationResults &other);

    ChargeValidationResults &operator=(const ChargeValidationResults &other);

    void reset();

    QString toString(Enums::TextType text_type) const;
  };

  explicit IsotopicCluster(QObject *parent = nullptr);
  IsotopicCluster(pappso::Trace profile_trace, QObject *parent = nullptr);
  IsotopicCluster(pappso::Trace profile_trace,
                  pappso::Trace centroided_trace,
                  QObject *parent = nullptr);

  void setHighResPeakPickerParameters(
    const HighResPeakPickerParameters &high_res_peak_picker_parameters);

  void setLocalSignalToNoiseEstimatorParameters(
    const LocalSignalToNoiseEstimator::Parameters
      &local_signal_to_noise_estimator_parameters);

  const pappso::Trace &getProfileTrace() const;
  const pappso::Trace &getcentroidedTrace() const;

  int extractCentroids();
  int determineCharge(ChargeValidationResults &charge_validation_results);

  void computeLinearRegression(const std::vector<double> &y,
                               double &slope,
                               double &intercept,
                               double &r2,
                               double &se_slope);

  double computePpmRMSE(const std::vector<double> &observed_mz, int z_cand);

  double computePairwiseCV(const std::vector<double> &mz_spacings);

  int
  determineChargeAdvanced(ChargeValidationResults &charge_validation_results);

  QString toString(Enums::TextType text_type);

  protected:
  pappso::Trace m_profileTrace;
  pappso::Trace m_centroidedTrace;
  int m_charge = -1;
  ChargeValidationResults m_chargeValidationResults;

  HighResPeakPickerParameters m_highResPeakPickerParameters;
  LocalSignalToNoiseEstimator::Parameters
    m_localSignalToNoiseEstimatorParameters;
};


} // namespace libXpertMassCore
} // namespace MsXpS
