#!python

# -*- coding: utf-8 -*-
# Copyright (C) Arianna I. Renzini 2024
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import argparse
import distutils
import os
from pathlib import Path

import numpy as np
from bilby.core.prior import Interped
from bilby.core.utils import infer_args_from_function_except_n_args
from gwpopulation.models.mass import SinglePeakSmoothedMassDistribution
from gwpopulation.models.redshift import MadauDickinsonRedshift
from gwpopulation.utils import xp

from popstock.PopulationOmegaGW import PopulationOmegaGW

"""
***
"""

parser = argparse.ArgumentParser()
parser.add_argument('-ns', '--number_samples',help="number of samples.",action="store", type=int, default=None)
parser.add_argument('-nt', '--number_trials',help="number of population trials.",action="store", type=int, default=10000)
parser.add_argument('-wf', '--waveform_approximant',help="Wavefrom approximant. Default is IMRPhenomD.",action="store", type=str, default='IMRPhenomD')
parser.add_argument('-rd', '--run_directory',help="Run directory.",action="store", type=str, default='./')
parser.add_argument('-sid', '--sample_index',help="sample index. Samples will be considered in order after this sample. Only considered if both number of samples and sample set are also provided. Default is 0.", action="store", type=int, default=0)
parser.add_argument('-fr', '--frequencies', help="txt file with frequencies to use for the spectrum calculation.",action="store", type=str, default=None)
parser.add_argument('-mp', '--multiprocess', help="If True (default), pools the DEdF calculation.", action="store", type=str, default='True')
args = parser.parse_args()

if args.multiprocess:
    args.multiprocess = bool(distutils.util.strtobool(args.multiprocess))
else:
    args.multiprocess = True

N_trials=args.number_trials
wave_approx=args.waveform_approximant 
rundir=Path(args.run_directory)

"""
***
"""

mass_obj = SinglePeakSmoothedMassDistribution()
redshift_obj = MadauDickinsonRedshift(z_max=10)

models = {
        'mass_model' : mass_obj,
        'redshift_model' : redshift_obj,
        }
if args.frequencies is None:
    freqs = np.arange(10, 2000, 2.5)
else:
    try:
        freqs = np.loadtxt(args.frequencies)
    except ValueError:
        raise ValueError(f"{args.frequencies} is not a txt file.")

newpop = PopulationOmegaGW(models=models, frequency_array=freqs)

Lambda_0 =  {'alpha': 3.5, 'beta': 1, 'delta_m': 4.5, 'lam': 0.04, 'mmax': 100, 'mmin': 4, 'mpp': 34, 'sigpp':4, 'gamma': 2.7, 'kappa': 5.6, 'z_peak': 1.9, 'rate': 15}
tag=f'{wave_approx}_{args.number_samples}_samples_{N_trials}_trials_Lambda_0_{args.sample_index}'

newpop.draw_and_set_proposal_samples(Lambda_0, N_proposal_samples=args.number_samples)
newpop.calculate_omega_gw(waveform_approximant=wave_approx, Lambda=Lambda_0, multiprocess=args.multiprocess)

np.savez(f"{os.path.join(rundir, f'omegagw_0_{tag}.npz')}", omega_gw=newpop.omega_gw, freqs=newpop.frequency_array, fiducial_samples=newpop.proposal_samples, Lambda_0=Lambda_0, draw_dict=newpop.pdraws)

exit()
