/*******************************************************************************
 * Copyright (c) 2025 Olivier Langella
 *<Olivier.Langella@universite-paris-saclay.fr>.
 *
 * This file is part of the PAPPSOms++ library.
 *
 *     PAPPSOms++ 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.
 *
 *     PAPPSOms++ 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 PAPPSOms++.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/


// ./tests/peptidoms/catch2-only-peptidoms [zea4542] -s


#include <catch2/catch_test_macros.hpp>
#include <catch2/catch_approx.hpp>
#include <catch2/matchers/catch_matchers_vector.hpp>

#include <QString>
#include "../common.h"
#include <pappsomspp/core/amino_acid/aastringcodemassmatching.h>
#include <pappsomspp/core/fasta/fastareader.h>
#include <pappsomspp/core/fasta/fastafileindexer.h>
#include <pappsomspp/core/massspectrum/massspectrum.h>
#include <pappsomspp/core/processing/filters/filterresample.h>
#include <pappsomspp/core/processing/filters/filterpass.h>
#include <pappsomspp/core/processing/filters/filterchargedeconvolution.h>
#include <pappsomspp/core/processing/specpeptidoms/correctiontree.h>
#include <pappsomspp/core/processing/specpeptidoms/locationsaver.h>
#include <pappsomspp/core/processing/specpeptidoms/semiglobalalignment.h>
#include <pappsomspp/core/processing/specpeptidoms/spomsspectrum.h>
#include <pappsomspp/core/processing/specpeptidoms/types.h>
#include <pappsomspp/core/protein/protein.h>
#include <pappsomspp/core/msfile/msfileaccessor.h>


TEST_CASE("test for peptidoms alignment.", "[zea4542]")
{
  // Set the debugging message formatting pattern.
  qSetMessagePattern(QString("%{file}@%{line}, %{function}(): %{message}"));

  SECTION("..:: Check precise alignment for GRMZM2G165901_P01 on spectrum 4542 ::..", "[zea4542]")
  {

    /// gorgone/pappso/moulon/database/Genome_Z_mays_5a.fasta
    //"GRMZM2G165901_P01"  spectrum_index= 4542

    /*
      >GRMZM2G165901_P01 P10979 Glycine-rich RNA-binding, abscisic acid-inducible protein
  seq=translation; coord=5:14072358..14073760:-1; parent_transcript=GRMZM2G165901_T01;
  parent_gene=GRMZM2G165901 MAAADVEYRCFVGGLAWATSNESLENAFASYGEILDSKVITDRETGRSRGFGFVTFSSEN
  SMLDAIENMNGKELDGRNITVNQAQSRGGGGGGGGYGGGRGGGGGYGGGRRDGGYGGGGG
  YGGRREGGGGGYGGGGGYGGRREGGGGGYGGGGGGGWRD
  */

    pappso::MsFileAccessor file_access(
      "/gorgone/pappso/data_extraction_pappso/mzML/20120906_balliau_extract_1_A01_urnb-1.mzML", "");
    pappso::MsRunReaderSPtr msrunA01 = file_access.getMsRunReaderSPtrByRunId("", "runa01");

    pappso::AaCode aa_code;
    aa_code.addAaModification('C', pappso::AaModification::getInstance("MOD:00397"));

    pappso::specpeptidoms::SpOMSProtein protein(
      "protein_id",
      "SMLDAIENMNGKELDGRNITVNQAQSRGGGGGGGGYGGGRGGGGGYGGGRRDGGYGGGGGYGGRREGGGGGYGGGGGYGGRREGGGGGYGGG"
      "GGGGWRD",
      aa_code);

    pappso::PrecisionPtr precision_ptr = pappso::PrecisionFactory::getDaltonInstance(0.02);

    pappso::QualifiedMassSpectrum spectrum_simple = msrunA01.get()->qualifiedMassSpectrum(4542);
    pappso::FilterChargeDeconvolution(precision_ptr)
      .filter(*(spectrum_simple.getMassSpectrumSPtr().get()));
    pappso::FilterResampleKeepGreater(150).filter(*(spectrum_simple.getMassSpectrumSPtr().get()));
    pappso::FilterGreatestY(120).filter(*(spectrum_simple.getMassSpectrumSPtr().get()));


    pappso::specpeptidoms::SpOMSSpectrum experimental_spectrum(
      spectrum_simple, precision_ptr, aa_code);


    pappso::specpeptidoms::ScoreValues score_values;

    pappso::specpeptidoms::SemiGlobalAlignment semi_global_alignment(
      score_values, precision_ptr, aa_code);

    qDebug();
    semi_global_alignment.fastAlign(experimental_spectrum, &protein); // 1er alignement

    qDebug();
    std::vector<pappso::specpeptidoms::Location> locations =
      semi_global_alignment.getLocationSaver()
        .getLocations(); // On récupère les sous-séquences intéressantes pour un alignement plus
                         // précis.

    qDebug();
    REQUIRE(locations.size() == 4);


    QStringList interpretation_list;
    for(auto loc : locations)
      {
        qDebug() << "loc.beginning=" << loc.beginning << " loc.length=" << loc.length;
        semi_global_alignment.preciseAlign(experimental_spectrum,
                                           &protein,
                                           loc.beginning,
                                           loc.length); // 2e alignement
        qDebug();
        pappso::specpeptidoms::Alignment best_alignment =
          semi_global_alignment.getBestAlignment(); // On récupère le meilleur alignement.

        interpretation_list << best_alignment.m_peptideModel.toInterpretation();
      }
  }

  SECTION("..:: Check precise alignment for GRMZM2G080930_P01 on spectrum 4542 ::..", "[zea4542]")
  {

    /// gorgone/pappso/moulon/database/Genome_Z_mays_5a.fasta
    //"GRMZM2G080930_P01"  spectrum_index= 4542
    /*

  GRMZM2G080930_P01:
MARVYVGNLDSRVTSGELEDEFRVFGVLRSVWIARKPPGFAFIDFDDRRDAEDAIRDLDGKNGWRVELSRNSSGRGGRDRYGGSESKCYECGETGHFARECRLRIGSGGLGSGRRRSRSRSRSRSRSRSRSRSRSPRYRRSPSYSRRSYSPRYRSPRRRSPSPARARSYSRSP
*/

    pappso::MsFileAccessor file_access(
      "/gorgone/pappso/data_extraction_pappso/mzML/20120906_balliau_extract_1_A01_urnb-1.mzML", "");
    pappso::MsRunReaderSPtr msrunA01 = file_access.getMsRunReaderSPtrByRunId("", "runa01");

    pappso::AaCode aa_code;
    aa_code.addAaModification('C', pappso::AaModification::getInstance("MOD:00397"));

    pappso::specpeptidoms::SpOMSProtein protein(
      "protein_id",
      "MARVYVGNLDSRVTSGELEDEFRVFGVLRSVWIARKPPGFAFIDFDDRRDAEDAIRDLDGKNGWRVELSRNSSGRGGRDRYGGSESKCYECG"
      "ETGHFARECRLRIGSGGLGSGRRRSRSRSRSRSRSRSRSRSRSPRYRRSPSYSRRSYSPRYRSPRRRSPSPARARSYSRSP",
      aa_code);

    pappso::PrecisionPtr precision_ptr = pappso::PrecisionFactory::getDaltonInstance(0.02);

    pappso::QualifiedMassSpectrum spectrum_simple = msrunA01.get()->qualifiedMassSpectrum(4542);
    pappso::FilterChargeDeconvolution(precision_ptr)
      .filter(*(spectrum_simple.getMassSpectrumSPtr().get()));
    pappso::FilterResampleKeepGreater(150).filter(*(spectrum_simple.getMassSpectrumSPtr().get()));
    pappso::FilterGreatestY(120).filter(*(spectrum_simple.getMassSpectrumSPtr().get()));


    pappso::specpeptidoms::SpOMSSpectrum experimental_spectrum(
      spectrum_simple, precision_ptr, aa_code);


    pappso::specpeptidoms::ScoreValues score_values;

    pappso::specpeptidoms::SemiGlobalAlignment semi_global_alignment(
      score_values, precision_ptr, aa_code);

    qDebug();
    semi_global_alignment.fastAlign(experimental_spectrum, &protein); // 1er alignement

    qDebug();
    std::vector<pappso::specpeptidoms::Location> locations =
      semi_global_alignment.getLocationSaver()
        .getLocations(); // On récupère les sous-séquences intéressantes pour un alignement plus
                         // précis.

    qDebug();
    REQUIRE(locations.size() == 2);


    QStringList interpretation_list;
    for(auto loc : locations)
      {
        qDebug() << "loc.beginning=" << loc.beginning << " loc.length=" << loc.length;
        semi_global_alignment.preciseAlign(experimental_spectrum,
                                           &protein,
                                           loc.beginning,
                                           loc.length); // 2e alignement
        qDebug();
        pappso::specpeptidoms::Alignment best_alignment =
          semi_global_alignment.getBestAlignment(); // On récupère le meilleur alignement.

        interpretation_list << best_alignment.m_peptideModel.toInterpretation();
      }
  }
}
