#!/usr/bin/env python
"""
The program combines output files generated
by pycbc_sngls_findtrigs to generate a mapping between SNR and FAP/FAR, along
with producing the combined foreground and background triggers.
"""

import argparse
import logging

import numpy

import pycbc.conversions as conv
import pycbc.io
import pycbc.pnutils
from pycbc.events import significance

logger = logging.getLogger(__name__)


class FileWriter:
    def __init__(self, name):
        self.f = pycbc.io.HFile(name, "w")
        self.attrs = self.f.attrs

    def __setitem__(self, name, data):
        # Make a new item if isn't in the hdf file
        if name not in self.f:
            self.f.create_dataset(
                name,
                data=data,
                compression="gzip",
                compression_opts=9,
                shuffle=True,
                maxshape=data.shape,
            )
        # Else reassign values
        else:
            self.f[name][:] = data

    def __getitem__(self, *args):
        return self.f.__getitem__(*args)


parser = argparse.ArgumentParser()
# General required options
pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "--sngls-files",
    nargs="+",
    help="List of files containign trigger and statistic information.",
)
parser.add_argument(
    "--full-data-background",
    required=True,
    help="background file from full data for use in analyzing injection coincs",
)
parser.add_argument(
    "--ifos", nargs=1, help="List of ifos used in these coincidence files"
)
parser.add_argument(
    "--cluster-window",
    type=float,
    default=10,
    help="Length of time window in seconds to cluster coinc events [default=10s]",
)
parser.add_argument(
    "--veto-window",
    type=float,
    default=0.1,
    help="Time around each zerolag trigger to window out [default=.1s]",
)
significance.insert_significance_option_group(parser)
parser.add_argument("--output-file")
args = parser.parse_args()

pycbc.init_logging(args.verbose)

significance.check_significance_options(args, parser)

logger.info("Loading triggers")
logger.info("IFO input: %s", args.ifos[0])
all_trigs = pycbc.io.MultiifoStatmapData(files=args.sngls_files, ifos=args.ifos)
ifo = args.ifos[0]
assert ifo + "/time" in all_trigs.data

logger.info("We have %s triggers", len(all_trigs.stat))
logger.info("Clustering triggers")
all_trigs = all_trigs.cluster(args.cluster_window)

logger.info("getting background statistics")

fb = pycbc.io.HFile(args.full_data_background, "r")
back_stat = fb["background/stat"][:]
back_stat_exc = fb["background_exc/stat"][:]

bkg_dec_facs = fb["background/decimation_factor"][:]
bkg_exc_dec_facs = fb["background_exc/decimation_factor"][:]

# For now, all triggers are both in the foreground and background
fore_locs = numpy.flatnonzero(all_trigs.timeslide_id == 0)

fg_time = fb.attrs["background_time"]
fg_time_exc = fb.attrs["background_time_exc"]

logger.info("Dumping foreground triggers")
f = FileWriter(args.output_file)
f.attrs["num_of_ifos"] = 1
f.attrs["ifos"] = ifo

f.attrs["timeslide_interval"] = all_trigs.attrs["timeslide_interval"]

# Copy over the segment info
for key in all_trigs.seg:
    f[f"segments/{key}/start"] = all_trigs.seg[key]["start"][:]
    f[f"segments/{key}/end"] = all_trigs.seg[key]["end"][:]

f["segments/foreground_veto/start"] = numpy.array([0])
f["segments/foreground_veto/end"] = numpy.array([0])
for k in all_trigs.data:
    f["foreground/" + k] = all_trigs.data[k]


logger.info("Estimating FAN from background statistic values")
# Ranking statistic of foreground and background
fore_stat = all_trigs.stat[fore_locs]

significance_dict = significance.digest_significance_options([ifo], args)

# Cumulative array of exclusive background triggers and the number
# of exclusive background triggers louder than each foreground trigger
bg_far_exc, fg_far_exc, sig_info = significance.get_far(
    back_stat_exc, fore_stat, bkg_exc_dec_facs, fg_time_exc, **significance_dict[ifo]
)

fg_far_exc = significance.apply_far_limit(fg_far_exc, significance_dict, combo=ifo)
bg_far_exc = significance.apply_far_limit(bg_far_exc, significance_dict, combo=ifo)

fg_ifar_exc = 1.0 / fg_far_exc
bg_ifar_exc = 1.0 / bg_far_exc

f["background_exc/ifar"] = conv.sec_to_year(bg_ifar_exc)
f.attrs["background_time_exc"] = fg_time_exc
f.attrs["foreground_time_exc"] = fg_time_exc

fap_exc = 1 - numpy.exp(-fg_time_exc / fg_ifar_exc)
f["foreground/ifar_exc"] = conv.sec_to_year(fg_ifar_exc)
f["foreground/fap_exc"] = fap_exc

for key, value in sig_info.items():
    f["foreground"].attrs[key + "_exc"] = value

if "name" in all_trigs.attrs:
    f.attrs["name"] = all_trigs.attrs["name"]

logger.info("Done!")
