#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TLorentzVector.h"
#include "TEfficiency.h"

#include <vector>
#include <iostream>

using namespace std;

enum LIMITS {
    MAX_TRACKS = 30000,
};

bool is_in_fv(const TLorentzVector &pos, const float margin = 20)
{
    if (pos.X() > 3 + margin && pos.X() < 253 - margin && pos.Y() > -113 + margin && pos.Y() < 113 - margin &&
        pos.Z() > 3 + margin && pos.Z() < 1034 - margin) {
        return true;
    }

    return false;
}

bool is_in_fv(const float x, const float y, const float z, const float margin = 20)
{
    TLorentzVector pos(x, y, z, 0);
    return is_in_fv(pos, margin);
}

bool is_good_proton(const TLorentzVector &start, const TLorentzVector &end, const float proton_daugher_ke,
                    const float max_proton_daugher_ke = 0)
{
    if (is_in_fv(start, 0) && is_in_fv(end, 0) && proton_daugher_ke <= max_proton_daugher_ke) {
        return true;
    }
    return false;
}

TH1 *resolution_hist(TH2 *in)
{
    TString basename(in->GetName());
    auto current_dir = in->GetDirectory();
    in->FitSlicesY();
    auto mean = (TH1 *) current_dir->Get(basename + "_1");
    auto sigma = (TH1 *) current_dir->Get(basename + "_2");
    auto out = (TH1 *) mean->Clone(basename + "res");
    for (int ix = 1; ix < out->GetNbinsX(); ++ix) {
        out->SetBinError(ix, sigma->GetBinContent(ix));
    }
    return out;
}

bool particle_match(const TLorentzVector &pa, const TLorentzVector &pb, const TLorentzVector &ma,
                    const TLorentzVector &mb)
{
    // pos + direction
    // if (fabs(pa.X() - pb.X() + 0.1) > 0.5) return false;
    // if (fabs(pa.Y() - pb.Y()) > 1.) return false;
    // if (fabs(pa.Z() - pb.Z()) > 1.) return false;
    // if (fabs(ma.Theta() - mb.Theta()) > 0.5) return false;
    // if (fabs(ma.Phi() - mb.Phi()) > 0.5) return false;

    // dist
    auto dist = (pa - pb).Vect();
    if (dist.Mag() > 1.) return false;

    // if (fabs(ma.Theta() - mb.Theta()) > 1.0) return false;
    // if (fabs(ma.Phi() - mb.Phi()) > 1.0) return false;

    return true;
}

void numu_energy(
    // const char *input = "data/nu_overlay_run2.root"
    const char *input = "data-orig/checkout_prodgenie_bnb_nu_overlay_run1.root")
{
    const int target_pdg = 13;  // 11, 13, 2212

    gInterpreter->GenerateDictionary("vector<vector<int> >", "vector");

    auto *tf = TFile::Open(input, "read");
    auto *dir = (TDirectoryFile *) tf->Get("wcpselection");

    // old
    // auto *T_PFDump = (TTree *) dir->Get("T_PFDump");
    // auto *T_PFeval = (TTree *) dir->Get("T_PFeval");
    // T_PFDump->AddFriend(T_PFeval);

    // new
    auto *T_PFDump = (TTree *) dir->Get("T_PFeval");

    auto *T_KINEvars = (TTree *) dir->Get("T_KINEvars");
    T_PFDump->AddFriend(T_KINEvars);
    auto *T_eval = (TTree *) dir->Get("T_eval");
    T_PFDump->AddFriend(T_eval);
    auto *T_BDTvars = (TTree *) dir->Get("T_BDTvars");
    T_PFDump->AddFriend(T_BDTvars);

    bool truth_isCC;
    float truth_nu_momentum[4];
    float truth_corr_nuvtxX;
    float truth_corr_nuvtxY;
    float truth_corr_nuvtxZ;
    float reco_nuvtxX;
    float reco_nuvtxY;
    float reco_nuvtxZ;

    float numu_cc_flag;

    float stm_clusterlength;
    bool truth_isFC;
    bool match_isFC;

    float kine_reco_Enu;
    std::vector<float> *kine_energy_particle = 0;
    std::vector<int> *kine_energy_info = 0;
    std::vector<int> *kine_particle_type = 0;

    T_PFDump->SetBranchAddress("truth_isCC", &truth_isCC);
    T_PFDump->SetBranchAddress("truth_nu_momentum", &truth_nu_momentum);
    T_PFDump->SetBranchAddress("truth_corr_nuvtxX", &truth_corr_nuvtxX);
    T_PFDump->SetBranchAddress("truth_corr_nuvtxY", &truth_corr_nuvtxY);
    T_PFDump->SetBranchAddress("truth_corr_nuvtxZ", &truth_corr_nuvtxZ);
    T_PFDump->SetBranchAddress("reco_nuvtxX", &reco_nuvtxX);
    T_PFDump->SetBranchAddress("reco_nuvtxY", &reco_nuvtxY);
    T_PFDump->SetBranchAddress("reco_nuvtxZ", &reco_nuvtxZ);

    T_PFDump->SetBranchAddress("numu_cc_flag", &numu_cc_flag);  // T_BDTvars

    T_PFDump->SetBranchAddress("stm_clusterlength", &stm_clusterlength);  // T_eval
    T_PFDump->SetBranchAddress("truth_isFC", &truth_isFC);                // T_eval
    T_PFDump->SetBranchAddress("match_isFC", &match_isFC);                // T_eval

    T_PFDump->SetBranchAddress("kine_energy_particle", &kine_energy_particle);
    T_PFDump->SetBranchAddress("kine_energy_info", &kine_energy_info);
    T_PFDump->SetBranchAddress("kine_particle_type", &kine_particle_type);
    T_PFDump->SetBranchAddress("kine_reco_Enu", &kine_reco_Enu);

    TH1F *h_ke_energy_info = new TH1F("h_ke_energy_info", "h_ke_energy_info", 5, -1.5, 3.5);

    TH1F *h_reco_m_truth = new TH1F("h_reco_m_truth", "h_reco_m_truth", 100, -1, 1);

    // TH2F *h_reco_v_truth = new TH2F("h_reco_v_truth", "h_reco_v_truth", 100, 0, 2, 100, 0, 2); // energy
    TH2F *h_reco_v_truth = new TH2F("h_reco_v_truth", "h_reco_v_truth", 20, 0, 2, 40, -2, 2);  // energy bias
    // TH2F *h_reco_v_truth = new TH2F("h_reco_v_truth", "h_reco_v_truth", 20, 0, 3, 100, -TMath::Pi(), TMath::Pi()); //
    // TH2F *h_reco_v_truth = new TH2F("h_reco_v_truth", "h_reco_v_truth", 10, 0, 3, 100, -3, 3);  // angle
    // TH2F *h_reco_v_truth = new TH2F("h_reco_v_truth", "h_reco_v_truth", 20, 0, 3, 100, -1, 1);  // tmp

    TH1F *h_truth_e_all = new TH1F("h_truth_e_all", "h_truth_e_all", 60, 0, 3);
    TH1F *h_truth_e_match = new TH1F("h_truth_e_match", "h_truth_e_match", 60, 0, 3);

    int counter_all = 0;
    int counter_pass = 0;
    for (int ientry = 0; ientry < T_PFDump->GetEntries(); ++ientry) {
    // for (int ientry = 0; ientry < 10000; ++ientry) {
        ++counter_all;
        T_PFDump->GetEntry(ientry);
        if (ientry % (T_PFDump->GetEntries()/10) == 0) cout << "processing: " << ientry*100 / T_PFDump->GetEntries() << "%" << endl;
        if (numu_cc_flag < 0 || stm_clusterlength < 15) continue;  // generic nu selection
        if (!truth_isCC) continue;
        if (match_isFC!=true) continue; // FV cut
        // if (!is_in_fv(truth_corr_nuvtxX, truth_corr_nuvtxY, truth_corr_nuvtxZ)) continue; // alternative FV

        // TVector3 truth_nuvtx(truth_corr_nuvtxX, truth_corr_nuvtxY, truth_corr_nuvtxZ);
        // TVector3 reco_nuvtx(reco_nuvtxX, reco_nuvtxY, reco_nuvtxZ);
        // if ((reco_nuvtx - truth_nuvtx).Mag() > 1.0) continue;
        ++counter_pass;

        // find ke_energy_info
        int selected_ke_energy_info = -1;
        bool all_method1 = true;
        float max_kine_energy_particle = -1;
        for (size_t ikine = 0; ikine < kine_energy_particle->size(); ++ikine) {
            if ((*kine_particle_type)[ikine] != target_pdg) continue;
            if ((*kine_energy_particle)[ikine]!=1) all_method1 = false;
            if ((*kine_energy_particle)[ikine] > max_kine_energy_particle) {
                max_kine_energy_particle = (*kine_energy_particle)[ikine];
                selected_ke_energy_info = (*kine_energy_info)[ikine];
            }
        }
        h_ke_energy_info->Fill(selected_ke_energy_info);

        // h_reco_v_truth->Fill(truth_nu_momentum[3], (kine_reco_Enu / 1000. - truth_nu_momentum[3]) / truth_nu_momentum[3]);
        if (all_method1) {
            h_reco_v_truth->Fill(truth_nu_momentum[3], (kine_reco_Enu / 1000. - truth_nu_momentum[3]) / truth_nu_momentum[3]);
        }
        if (selected_ke_energy_info == 0) {
            // h_reco_v_truth->Fill(truth_nu_momentum[3], (kine_reco_Enu / 1000. - truth_nu_momentum[3]) / truth_nu_momentum[3]);
        }
    }
    cout << "target: truth " << counter_all << "; reco " << counter_pass
         << "; ratio: " << 100. * counter_pass / counter_all << "%" << endl;

    const int LINE_WIDTH = 2;

    TCanvas *c0 = new TCanvas("c0", "c0");
    h_truth_e_all->SetLineColor(kBlack);
    h_truth_e_all->SetLineWidth(LINE_WIDTH);
    h_truth_e_all->SetTitle(";E^{truth} [GeV]");
    h_truth_e_all->Draw();
    h_truth_e_match->SetLineColor(kRed);
    h_truth_e_match->SetLineWidth(LINE_WIDTH);
    h_truth_e_match->Draw("same");

    TCanvas *c1 = new TCanvas("c1", "c1");
    c1->SetGrid();
    auto pEff = new TEfficiency(*h_truth_e_match, *h_truth_e_all);
    // pEff->GetXaxis()->SetRangeUser(0,1);
    pEff->SetMarkerStyle(20);
    pEff->SetTitle(";E^{truth} [GeV];Efficiency");
    pEff->Draw("ap");
    // auto h_truth_e_ratio = (TH1F *) h_truth_e_match->Clone("h_truth_e_ratio");
    // h_truth_e_ratio->Divide(h_truth_e_all);
    // h_truth_e_ratio->SetLineColor(kRed);
    // h_truth_e_ratio->SetLineWidth(LINE_WIDTH);
    // h_truth_e_ratio->SetTitle(";E^{truth} [GeV];Efficiency");
    // h_truth_e_ratio->SetStats(0);
    // h_truth_e_ratio->Draw("");

    TCanvas *c2 = new TCanvas("c2", "c2");
    c2->SetGrid();
    c2->SetLogz();
    // h_reco_v_truth->SetTitle(";Z^{truth} [cm];Z^{reco}-Z^{truth} [cm]");
    // h_reco_v_truth->SetTitle(";#phi^{truth} [rad];#phi^{reco}-#phi^{truth} [rad]");
    h_reco_v_truth->SetTitle(";E^{truth} [GeV];bias");
    // h_reco_v_truth->SetTitle(";E^{truth} [GeV];E^{reco} [GeV]");
    // h_reco_v_truth->SetTitle(";E^{truth} [GeV];#Delta #theta");
    // h_reco_v_truth->SetTitle(";E^{truth} [GeV];#Delta #phi");
    // h_reco_v_truth->SetStats(0);
    h_reco_v_truth->SetMinimum(1);
    h_reco_v_truth->Draw("colz");

    // resolution_hist
    auto h_reco_v_truth_1 = resolution_hist(h_reco_v_truth);
    h_reco_v_truth_1->Draw("e,same");

    TCanvas *c3 = new TCanvas("c3", "c3");
    c3->SetGrid();
    // h_reco_m_truth->SetTitle(";|Vtx^{reco}-Vtx^{truth}| [cm]");
    // h_reco_m_truth->SetTitle(";X^{reco}-X^{truth} [cm]");
    // h_reco_m_truth->SetTitle(";#phi^{reco}-#phi^{truth} [rad]");
    h_reco_m_truth->SetTitle(";E^{reco}-E^{truth} [GeV]");
    // h_reco_m_truth->SetStats(0);
    h_reco_m_truth->Draw();

    TCanvas *c5 = new TCanvas("c5", "c5");
    h_ke_energy_info->Draw("text");
}
