/* 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>

#include <Eigen/Dense>

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


namespace MsXpS
{
namespace libXpertMassCore
{


class DECLSPEC IsotopicCluster: public QObject
{
  Q_OBJECT

  public:
  /*
   Bitwise stuff (from StackOverflow)

It is sometimes worth using an enum to name the bits:

enum ThingFlags = {
ThingMask  = 0x0000,
ThingFlag0 = 1 << 0,
ThingFlag1 = 1 << 1,
ThingError = 1 << 8,
}

Then use the names later on. I.e. write

thingstate |= ThingFlag1;
thingstate &= ~ThingFlag0;
if (thing & ThingError) {...}

to set, clear and test. This way you hide the magic numbers from the rest of
your code.
*/

  enum class DECLSPEC OutputStringElements : int
  {
    NOT_SET                   = 0x000,
    CHARGE_VALIDATION_RESULTS = 1 << 0,
    INPUT_ISOTOPIC_CLUSTER    = 1 << 1,
    OUTPUT_ISOTOPIC_CLUSTER   = 1 << 2,
    MASS_ESTIMATIONS          = 1 << 3,
  };
  // Overload bitwise operators
  friend inline OutputStringElements
  operator&(OutputStringElements lhs, OutputStringElements rhs)
  {
    return static_cast<OutputStringElements>(
      static_cast<std::underlying_type_t<OutputStringElements>>(lhs) &
      static_cast<std::underlying_type_t<OutputStringElements>>(rhs));
  }

  friend inline OutputStringElements
  operator|(OutputStringElements lhs, OutputStringElements rhs)
  {
    return static_cast<OutputStringElements>(
      static_cast<std::underlying_type_t<OutputStringElements>>(lhs) |
      static_cast<std::underlying_type_t<OutputStringElements>>(rhs));
  }

  enum class DECLSPEC AverageMassDeterminationMethod : int
  {
    NOT_SET                 = 0x000,
    MZ_WEIGHTED_INTENSITIES = 1 << 0,
    CLUSTER_MODE            = 1 << 1,
    GAUSSIAN_FIT_LEAST_SQUARES = 1 << 2,
    GAUSSIAN_FIT_LEV_MARQ      = 1 << 3,
    LAST                       = 1 << 4,
  };
  static DECLSPEC QMap<int, QString> averageMassDeterminationMethodMap;

  // Overload bitwise operators
  friend inline AverageMassDeterminationMethod
  operator&(AverageMassDeterminationMethod lhs,
            AverageMassDeterminationMethod rhs)
  {
    return static_cast<AverageMassDeterminationMethod>(
      static_cast<std::underlying_type_t<AverageMassDeterminationMethod>>(lhs) &
      static_cast<std::underlying_type_t<AverageMassDeterminationMethod>>(rhs));
  }

  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
    // 95% Confidence Interval Lower Bound
    double chargeConfidenceIntervalLower = 0.0;
    // 95% Confidence Interval Upper Bound
    double chargeConfidenceIntervalUpper = 0.0;
    // Tells if determined charge is in [ -0.5, + 0.5 ] interval.
    bool isChargeInsideIntegerInterval   = false;

    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(const pappso::Trace &profile_trace,
                  QObject *parent = nullptr);
  IsotopicCluster(pappso::Trace &&profile_trace, QObject *parent = nullptr);

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

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

  IsotopicCluster(const IsotopicCluster &other, QObject *parent = nullptr);

  void
  setHighResPeakPickerParameters(const Processing::HighResPeakPickerParameters
                                   &high_res_peak_picker_parameters);

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

  void setProfileTrace(const pappso::Trace &profile_trace);
  void setProfileTrace(pappso::Trace &&profile_trace);

  const pappso::Trace &getProfileTrace() const;
  const pappso::Trace &getCentroidedTrace() const;
  const pappso::Trace &getGaussianFitTrace() const;

  void setAveragine(const Averagine &averagine);
  const Averagine &getAveragine() const;

  static QString getAvgMassDeterminationMethod(int method);
  static QString
  getAvgMassDeterminationMethod(AverageMassDeterminationMethod method);

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

  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);

  std::tuple<double, double, double>
  computelinearLeastSquaresGaussianForCentroids();
  std::tuple<double, double, double, double>
  computeLevenbergMarquardtGaussianForCentroids();

  // This is the first step to monoisotopic mass estimation, because
  // the centroided trace contains m/z centroids, not Mr centroids.
  // It is a determination, not an estimation, because it can be derived
  // from looking at the data without Averagine logic. Averagine logic
  // comes later when *estimating* the monoisotopic m/z & Mr.
  double determineAvgMz(AverageMassDeterminationMethod determination_method =
                          AverageMassDeterminationMethod::NOT_SET);
  double determineAvgMzWeightedIntensities();
  double determineAvgMzClusterMode();
  double determineAvgMzGaussianFit(
    AverageMassDeterminationMethod method =
      AverageMassDeterminationMethod::GAUSSIAN_FIT_LEAST_SQUARES);
  double getAvgMz();

  double determineAvgMr(AverageMassDeterminationMethod determination_method =
                          AverageMassDeterminationMethod::NOT_SET);

  double computeAvgMr();
  double getAvgMr();

  double estimateMonoMz(AverageMassDeterminationMethod determination_method =
                          AverageMassDeterminationMethod::NOT_SET);
  double estimateMonoMz(const Averagine &averagine);

  double estimateMonoMr(AverageMassDeterminationMethod determination_method =
                          AverageMassDeterminationMethod::NOT_SET);
  double estimateMonoMr(const Averagine &averagine);
  // There is the private estimateClusterModeMonoMr().

  QString toString(OutputStringElements output_string_elements,
                   Enums::TextType text_type) const;

  protected:
  pappso::Trace m_profileTrace;    // These are m/z values !
  pappso::Trace m_centroidedTrace; // These are m/z values !
  pappso::Trace m_gaussianFitTrace;

  int m_charge = 0;
  Averagine m_averagine;

  AverageMassDeterminationMethod m_avgMassDeterminationMethod =
    AverageMassDeterminationMethod::MZ_WEIGHTED_INTENSITIES;

  double m_avgMz  = 0;
  double m_avgMr  = 0;
  double m_monoMz = 0;
  double m_monoMr = 0;

  ChargeValidationResults m_chargeValidationResults;

  Processing::HighResPeakPickerParameters m_highResPeakPickerParameters;
  Processing::LocalSignalToNoiseEstimator::Parameters
    m_localSignalToNoiseEstimatorParameters;

  private:
  double estimateClusterModeMonoMr();
};


} // namespace libXpertMassCore
} // namespace MsXpS
