#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 match_e(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 vertex_eff(
    // const char *input = "data/nue_overlay_run2.root"
    const char *input = "data/nu_overlay_run2.root"
    )
{
    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);

    int run;
    int subrun;
    int event;

    int truth_Ntrack;
    int truth_id[MAX_TRACKS];
    int truth_pdg[MAX_TRACKS];
    int truth_process[MAX_TRACKS];
    int truth_mother[MAX_TRACKS];
    float truth_startXYZT[MAX_TRACKS][4];
    float truth_endXYZT[MAX_TRACKS][4];
    float truth_startMomentum[MAX_TRACKS][4];
    float truth_endMomentum[MAX_TRACKS][4];
    std::vector<std::vector<int> > *truth_daughters = 0;

    int reco_Ntrack;
    int reco_id[MAX_TRACKS];
    int reco_pdg[MAX_TRACKS];
    int reco_process[MAX_TRACKS];
    int reco_mother[MAX_TRACKS];
    float reco_startXYZT[MAX_TRACKS][4];
    float reco_endXYZT[MAX_TRACKS][4];
    float reco_startMomentum[MAX_TRACKS][4];
    float reco_endMomentum[MAX_TRACKS][4];
    std::vector<std::vector<int> > *reco_daughters = 0;

    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 nue_score;
    float numu_score;

    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("run", &run);
    T_PFDump->SetBranchAddress("subrun", &subrun);
    T_PFDump->SetBranchAddress("event", &event);

    T_PFDump->SetBranchAddress("truth_Ntrack", &truth_Ntrack);
    T_PFDump->SetBranchAddress("truth_id", &truth_id);
    T_PFDump->SetBranchAddress("truth_pdg", &truth_pdg);
    T_PFDump->SetBranchAddress("truth_mother", &truth_mother);
    T_PFDump->SetBranchAddress("truth_startXYZT", &truth_startXYZT);
    T_PFDump->SetBranchAddress("truth_endXYZT", &truth_endXYZT);
    T_PFDump->SetBranchAddress("truth_startMomentum", &truth_startMomentum);
    T_PFDump->SetBranchAddress("truth_daughters", &truth_daughters);

    T_PFDump->SetBranchAddress("reco_Ntrack", &reco_Ntrack);
    T_PFDump->SetBranchAddress("reco_id", &reco_id);
    T_PFDump->SetBranchAddress("reco_pdg", &reco_pdg);
    T_PFDump->SetBranchAddress("reco_mother", &reco_mother);
    T_PFDump->SetBranchAddress("reco_startXYZT", &reco_startXYZT);
    T_PFDump->SetBranchAddress("reco_endXYZT", &reco_endXYZT);
    T_PFDump->SetBranchAddress("reco_startMomentum", &reco_startMomentum);
    T_PFDump->SetBranchAddress("reco_daughters", &reco_daughters);

    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_BDTvars
    T_PFDump->SetBranchAddress("numu_cc_flag", &numu_cc_flag);
    T_PFDump->SetBranchAddress("nue_score", &nue_score);
    T_PFDump->SetBranchAddress("numu_score", &numu_score);

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

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

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

    TH1F *h_dist = new TH1F("h_dist", "h_dist", 50, 0, 5);

    // angle
    // TH1F *h_truth_e_all = new TH1F("h_truth_e_all", "h_truth_e_all", 60, 0, TMath::Pi());
    // TH1F *h_truth_e_match = new TH1F("h_truth_e_match", "h_truth_e_match", 60, 0, TMath::Pi());

    int counter_all = 0;
    int counter_pass = 0;
    for (int ientry = 0; ientry < T_PFDump->GetEntries(); ++ientry) {
    // for (int ientry = 0; ientry < 10000; ++ientry) {
        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; // pass generic nu selection
        if (truth_isCC) continue;
        if (!is_in_fv(truth_corr_nuvtxX, truth_corr_nuvtxY, truth_corr_nuvtxZ)) continue;
        // if (match_isFC!=true) continue; // FV cut
        
        ++counter_all;
        h_truth_e_all->Fill(truth_nu_momentum[3]);
        TVector3 truth_nuvtx(truth_corr_nuvtxX, truth_corr_nuvtxY, truth_corr_nuvtxZ);
        TVector3 reco_nuvtx(reco_nuvtxX, reco_nuvtxY, reco_nuvtxZ);
        h_dist->Fill((reco_nuvtx - truth_nuvtx).Mag());
        if ((reco_nuvtx - truth_nuvtx).Mag() > 1.0) continue;
        ++counter_pass;
        // h_truth_e_match->Fill(truth_nu_momentum[3]);
        // h_truth_e_match->Fill(target_mom_start_truth.E());
        h_truth_e_match->Fill(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");
    auto h_cdf = h_dist->GetCumulative();
    h_cdf->Scale(1./counter_all);
    h_cdf->SetLineColor(kBlue);
    h_cdf->SetLineWidth(LINE_WIDTH);
    h_cdf->SetTitle(";|Vtx^{reco}-Vtx^{truth}| [cm]");
    h_cdf->Draw("e,text");
    h_cdf->GetYaxis()->SetRangeUser(0,1);

    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->SetTitle(";#theta_{YZ};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("");
}
