#!python

# Copyright (C) 2015 Andrew R. Williamson, Francesco Pannarale
#
# 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.

"""
Make workflow for the archival, targeted, coherent inspiral pipeline.
"""

import argparse
import logging
import os
import sys

import matplotlib

matplotlib.use("agg")

from igwn_segments import segment, segmentlist, segmentlistdict

import pycbc.workflow as _workflow
from pycbc import add_common_pycbc_options, init_logging
from pycbc.events.veto import select_segments_by_definer
from pycbc.results import layout, save_workflow_log
from pycbc.results.pygrb_plotting_utils import make_grb_segments_plot
from pycbc.workflow.core import FileList, SegFile, configparser_value_to_file
from pycbc.workflow.injection import compute_inj_optimal_snr
from pycbc.workflow.psd import make_psd_file

logger = logging.getLogger(__name__)

workflow_name = "pygrb_offline"

# Parse command line options and instantiate pycbc workflow object
parser = argparse.ArgumentParser()
add_common_pycbc_options(parser)
_workflow.add_workflow_command_line_group(parser)
_workflow.add_workflow_settings_cli(parser)
args = parser.parse_args()

init_logging(args.verbose, default_level=1)

container_wf = _workflow.Workflow(args, workflow_name)
main_wf = _workflow.Workflow(args, workflow_name + "-main")
finalize_wf = _workflow.Workflow(args, workflow_name + "-finalization")
tags = []

logger.info("Generating %s workflow", workflow_name)

# Options for features that have been removed: stop rather than ignore them
for section, option in [
    ("workflow-condition_strain", "do-gating"),
    ("workflow-inspiral", "ipn-search-points"),
    ("workflow-injections", "ipn-sim-points"),
]:
    if main_wf.cp.has_option(section, option):
        raise ValueError(f"[{section}] {option} is no longer supported.")

# Setup run directory
triggername = str(main_wf.cp.get("workflow", "trigger-name"))
output_dir = os.path.abspath(args.output_dir)
logger.info("Workflow will be generated in %s", output_dir)
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
os.chdir(output_dir)

# Setup results directory
rdir = layout.SectionNumber(
    os.path.join(output_dir, "post_processing", "webpage"),
    [
        "offsource_triggers_vs_time",
        "signal_consistency",
        "injections",
        "loudest_offsource_events",
        "exclusion_distances",
        "open_box",
        "workflow",
    ],
)
_workflow.makedir(rdir["workflow"])

# We are _also_ logging to a file
wf_log_file = _workflow.File(
    main_wf.ifos,
    "workflow-log",
    main_wf.analysis_time,
    extension=".txt",
    directory=rdir["workflow"],
)
init_logging(args.verbose, default_level=1, to_file=wf_log_file.storage_path)
logger.info("Created log file %s", wf_log_file.storage_path)

# SEGMENTS
triggertime = int(main_wf.cp.get("workflow", "trigger-time"))
start = triggertime - int(main_wf.cp.get("workflow-exttrig_segments", "max-duration"))
end = triggertime + int(main_wf.cp.get("workflow-exttrig_segments", "max-duration"))
main_wf.cp = _workflow.set_grb_start_end(main_wf.cp, start, end)

# Retrieve science segments
curr_dir = os.getcwd()
seg_dir = os.path.join(curr_dir, "segments")
sci_segs_file = _workflow.get_segments_file(
    main_wf, "science", "segments-science", seg_dir
)
sci_segs = {}
for ifo in main_wf.ifos:
    sci_segs[ifo] = sci_segs_file.segment_dict[ifo + ":science"]

# This block of code and PyCBCMultiInspiralExecutable.get_valid_times()
# must be consistent
if main_wf.cp.has_option("inspiral", "segment-start-pad"):
    pad_data = int(main_wf.cp.get("inspiral", "pad-data"))
    start_pad = int(main_wf.cp.get("inspiral", "segment-start-pad"))
    end_pad = int(main_wf.cp.get("inspiral", "segment-end-pad"))
    main_wf.cp.set("workflow-exttrig_segments", "min-before", str(start_pad + pad_data))
    main_wf.cp.set("workflow-exttrig_segments", "min-after", str(end_pad + pad_data))
elif main_wf.cp.has_option("inspiral", "analyse-segment-end"):
    safety = 1
    deadtime = int(main_wf.cp.get("inspiral", "segment-length")) / 2
    spec_len = int(main_wf.cp.get("inspiral", "inverse-spec-length")) / 2
    main_wf.cp.set(
        "workflow-exttrig_segments", "min-before", str(deadtime - spec_len - safety)
    )
    main_wf.cp.set("workflow-exttrig_segments", "min-after", str(spec_len + safety))
else:
    deadtime = int(main_wf.cp.get("inspiral", "segment-length")) / 4
    main_wf.cp.set("workflow-exttrig_segments", "min-before", str(deadtime))
    main_wf.cp.set("workflow-exttrig_segments", "min-after", str(deadtime))

# Do checks for no/single IFO case
single_ifo = main_wf.cp.has_option("workflow", "allow-single-ifo-search")
if len(sci_segs.keys()) == 0:
    make_grb_segments_plot(
        main_wf, segmentlistdict(), triggertime, triggername, seg_dir
    )
    logger.error("No science segments available.")
    sys.exit()
elif len(sci_segs.keys()) < 2 and not single_ifo:
    make_grb_segments_plot(
        main_wf, segmentlistdict(sci_segs), triggertime, triggername, seg_dir
    )
    msg = f"Science segments exist only for {next(iter(sci_segs.keys()))}. "
    msg += "If you wish to enable single IFO running add the option "
    msg += "'allow-single-ifo-search' to the [workflow] section of your "
    msg += "configuration file."
    logger.error(msg)
    sys.exit()

on_src, off_src, buffer_seg = _workflow.generate_triggered_segment(
    main_wf, seg_dir, sci_segs
)

sci_segs = segmentlistdict(sci_segs)
if on_src is None:
    logger.info("Making segment plot and exiting.")
    # `make_grb_segments_plot()` wants a single segment for fail_criterion.
    fail_criterion = off_src[main_wf.ifos[0]][0]
    make_grb_segments_plot(
        main_wf,
        sci_segs,
        triggertime,
        triggername,
        seg_dir,
        fail_criterion=fail_criterion,
    )
    sys.exit()

seg_files = _workflow.build_segment_filelist(seg_dir)
plot_met = make_grb_segments_plot(
    main_wf,
    sci_segs,
    triggertime,
    triggername,
    rdir.base,
    coherent_seg=off_src[next(iter(off_src.keys()))][0],
)
seg_plot = _workflow.File(plot_met[0], plot_met[1], plot_met[2], file_url=plot_met[3])
sci_segs = off_src

if len(sci_segs) == 1:
    logger.info("Generating a single IFO search.")
    mf_tag = "sngl"
elif len(sci_segs) > 1:
    mf_tag = "coherent"

# Update analysis time after coherent segment calculation
ifo = next(iter(sci_segs.keys()))
main_wf.cp = _workflow.set_grb_start_end(
    main_wf.cp, int(sci_segs[ifo][0][0]), int(sci_segs[ifo][0][1])
)

padding = int(main_wf.cp.get("inspiral", "pad-data"))

if main_wf.cp.has_option("inspiral", "segment-start-pad"):
    start_pad = int(main_wf.cp.get("inspiral", "segment-start-pad"))
    end_pad = int(main_wf.cp.get("inspiral", "segment-end-pad"))
    main_wf.analysis_time = segment(
        int(sci_segs[ifo][0][0]) + start_pad + padding,
        int(sci_segs[ifo][0][1]) - padding - end_pad,
    )
elif main_wf.cp.has_option("inspiral", "analyse-segment-end"):
    main_wf.analysis_time = segment(
        int(sci_segs[ifo][0][0]) + deadtime - spec_len + padding - safety,
        int(sci_segs[ifo][0][1]) - spec_len - padding - safety,
    )
else:
    main_wf.analysis_time = segment(
        int(sci_segs[ifo][0][0]) + deadtime + padding,
        int(sci_segs[ifo][0][1]) - deadtime - padding,
    )

# DATAFIND
df_dir = os.path.join(curr_dir, "datafind")
datafind_files, _, sci_segs, _ = _workflow.setup_datafind_workflow(
    main_wf, sci_segs, df_dir, sci_segs_file
)

ifos = sorted(sci_segs.keys())
main_wf.ifos = ifos

# input_files will contain:
# 1) the output files produced by the datafind
# 2) the veto file determined by looking up the segments being used
# 3) the sky grid file (if one is produced)
# 4) the bank-veto file
input_files = _workflow.FileList([])

# Convenience variable to operate on sci_segs within this executable
ifo = ifos[0]

input_files.extend(datafind_files)

# Retrieve vetoes
veto_file = None
if main_wf.cp.has_option("workflow-segments", "segments-vetoes"):
    veto_file = _workflow.get_segments_file(
        main_wf, "vetoes", "segments-vetoes", seg_dir, tags=["veto"]
    )
    input_files.append(veto_file)
    # Check that the onsource is free from vetoes
    for ifo in ifos:
        avail_segs = select_segments_by_definer(veto_file.storage_path, ifo=ifo)
        avail_segs.coalesce()
        # If no relevant vetoes are available, avail_segs becomes an empty list
        if len(avail_segs) > 0:
            vetoed_segs = off_src[ifo] - avail_segs
            if on_src[ifo].intersects(vetoed_segs):
                intersection = on_src[ifo] & vetoed_segs
                logger.error(
                    "The onsource %s contains the time %s that is vetoed in %s.",
                    on_src[ifo][0][:],
                    intersection,
                    ifo,
                )
                sys.exit()

# Generate sky grid if needed
skygrid_file = None
if main_wf.cp.has_option("workflow", "sky-error") or main_wf.cp.has_option(
    "workflow", "input-dist"
):
    logger.info("Generating sky-grid file.")
    skygrid_file = _workflow.make_skygrid_node(main_wf, df_dir, tags=["SEARCH"])
    input_files.extend(skygrid_file)

# Get bank_veto_bank.xml if running bank veto
if main_wf.cp.has_option("workflow-inspiral", "bank-veto-bank-file"):
    bank_veto_file = configparser_value_to_file(
        main_wf.cp, "workflow-inspiral", "bank-veto-bank-file"
    )
    bank_veto_file.description += "_BANK_VETO_BANK"
    bank_veto_file = _workflow.FileList([bank_veto_file])
    input_files.extend(bank_veto_file)

# TEMPLATE BANK AND SPLIT BANK
bank_files = _workflow.setup_tmpltbank_workflow(
    main_wf, sci_segs, datafind_files, df_dir
)
# Check there are not multiple banks
if len(bank_files) > 1:
    raise NotImplementedError("Multiple banks not supported")
full_bank_file = bank_files[0]
# Note: setup_splittable_workflow requires a FileList as input
splitbank_files = _workflow.setup_splittable_workflow(
    main_wf, bank_files, df_dir, tags=["inspiral"]
)

# --- TIME VARYING PSDS ---
# Directory where time-varying PSD files will be written
if main_wf.cp.has_section("calculate_psd"):
    psd_dir = os.path.join(output_dir, "psds")

    tv_psd_files = FileList([])

    for ifo in main_wf.ifos:
        logger.info("Creating time-varying PSD job for %s", ifo)

        # Segment file containing the FULL analysis segment
        psd_segfile = SegFile.from_segment_list(
            description=f"psd_{ifo}",
            segmentlist=segmentlist([main_wf.analysis_time]),
            name="psd",
            ifo=ifo,
            seg_summ_list=segmentlist([main_wf.analysis_time]),
            directory=psd_dir,
            extension="xml",
        )

        psd_file = make_psd_file(
            workflow=main_wf,
            frame_files=datafind_files.find_output_with_ifo(ifo),
            segment_file=psd_segfile,
            segment_name="psd",
            out_dir=psd_dir,
        )

        tv_psd_files.append(psd_file)

    logger.info("Created %d time-varying PSDs", len(tv_psd_files))

# INJECTIONS
injs = None
inj_tags = []
inj_files = None
inj_insp_files = None
if main_wf.cp.has_section("workflow-injections"):
    inj_dir = os.path.join(curr_dir, "injections")

    # Given the stretch of time this workflow will analyse, and the onsource
    # window with its buffer, generate the configuration file with the prior
    # for the injections times and add it to the config parser
    inj_method = main_wf.cp.get("workflow-injections", "injections-method")
    if inj_method == "IN_WORKFLOW" and main_wf.cp.has_option(
        "workflow-injections", "tc-prior-at-runtime"
    ):
        tc_path = os.path.join(output_dir, "tc_prior.ini")
        _workflow.generate_tc_prior(main_wf, tc_path, buffer_seg)

    # Generate injection files
    inj_files, inj_tags = _workflow.setup_injection_workflow(main_wf, inj_dir)
    injs = inj_files

    # Here we compute the optimal SNR for the injections before splitting them
    if main_wf.cp.has_section("optimal_snr"):
        if not main_wf.cp.has_section("calculate_psd"):
            raise ValueError("Optimal SNR calculation requires PSD estimation")

        snr_dir = os.path.join(inj_dir, "optimal_snr")

        optimal_snr_files = _workflow.FileList([])
        for inj, inj_tag in zip(injs, inj_tags, strict=True):
            snr_file = compute_inj_optimal_snr(
                main_wf, inj, tv_psd_files, snr_dir, tags=[inj_tag]
            )
            optimal_snr_files.append(snr_file)
            logger.info(
                "Optimal SNR workflow node created for injection tag %s", inj_tag
            )
        injs = optimal_snr_files
        inj_files = optimal_snr_files

    # Either split template bank for injections jobs or use same split banks
    # as for standard matched filter jobs
    if main_wf.cp.has_section("workflow-splittable-injections"):
        inj_splitbank_files = _workflow.setup_splittable_workflow(
            main_wf, bank_files, inj_dir, tags=["injections"]
        )
        for inj_split in inj_splitbank_files:
            split_str = [
                s
                for s in inj_split.tagged_description.split("_")
                if ("BANK" in s and s[-1].isdigit())
            ]
            if len(split_str) != 0:
                inj_split.tagged_description += (
                    f"{inj_split.tag_str}_{int(split_str[0].replace('BANK', ''))}"
                )
    else:
        inj_splitbank_files = _workflow.FileList([])
        inj_splitbank_files.extend(splitbank_files)

    # Split the injection files
    if main_wf.cp.has_section("workflow-splittable-split_inspinj"):
        inj_split_files = _workflow.FileList([])
        for inj_file, inj_tag in zip(inj_files, inj_tags, strict=True):
            file = _workflow.FileList([inj_file])
            inj_splits = _workflow.setup_splittable_workflow(
                main_wf, file, inj_dir, tags=["split_inspinj", inj_tag]
            )
            for inj_split in inj_splits:
                split_str = [
                    s
                    for s in inj_split.tagged_description.split("_")
                    if ("SPLIT" in s and s[-1].isdigit())
                ]
                if len(split_str) != 0:
                    new = inj_split.tagged_description.replace(
                        split_str[0],
                        f"SPLIT_{split_str[0].replace('SPLIT', '')}",
                    )
                    inj_split.tagged_description = new
            inj_split_files.extend(inj_splits)
        injs = inj_split_files

    # Generate injection matched filter workflow
    inj_insp_files = _workflow.setup_matchedfltr_workflow(
        main_wf,
        sci_segs,
        input_files,
        inj_splitbank_files,
        inj_dir,
        injs,
        tags=[mf_tag + "_injections"],
    )
    for inj_insp_file in inj_insp_files:
        split_str = [
            s
            for s in inj_insp_file.name.split("_")
            if ("SPLIT" in s and s[-1].isdigit())
        ]
        if len(split_str) != 0:
            num = split_str[0].replace("SPLIT", "_")
            inj_insp_file.tagged_description += num

# MAIN MATCHED FILTERING
insp_dir = os.path.join(curr_dir, "inspiral")
inspiral_files = _workflow.setup_matchedfltr_workflow(
    main_wf,
    sci_segs,
    input_files,
    splitbank_files,
    insp_dir,
    tags=[mf_tag + "_no_injections"],
)

# TODO: LONG TIME SLIDES

# POST-PROCESSING
pp_dir = os.path.join(curr_dir, "post_processing")
post_proc_method = main_wf.cp.get_opt_tags("workflow-postproc", "postproc-method", tags)
make_results = False
if post_proc_method == "PYGRB_OFFLINE":
    trig_comb_files, clustered_files, inj_find_files = (
        _workflow.setup_pygrb_pp_workflow(
            main_wf,
            pp_dir,
            seg_files,
            sci_segs[ifo][0],
            full_bank_file,
            inspiral_files,
            injs,
            inj_insp_files,
            inj_tags,
        )
    )
    sec_name = "workflow-pygrb_results_workflow"
    if not main_wf.cp.has_section(sec_name):
        msg = f"No {sec_name} section found in configuration file."
        logger.info(msg)
    else:
        logger.info("Entering results module")
        _workflow.setup_pygrb_results_workflow(
            main_wf,
            rdir,
            clustered_files,
            inj_files,
            inj_find_files,
            full_bank_file,
            seg_files,
            seg_plot,
            skygrid_file[0],
            veto_file=veto_file,
        )
        logger.info("Leaving results module")
        make_results = True

# COMPILE WORKFLOW AND WRITE DAX
container_wf += main_wf

# The results page reads the directory that the results are delivered to, so it
# must wait for the main workflow to finish, including its stage-out jobs
if make_results:
    _workflow.make_results_web_page(finalize_wf, rdir.base, template="red")
    container_wf += finalize_wf
    container_wf.add_subworkflow_dependancy(main_wf, finalize_wf)

container_wf.save()
logger.info("Written dax.")

# Close the log and flush to the html file
log_file_html = _workflow.File(
    main_wf.ifos,
    "WORKFLOW-LOG",
    main_wf.analysis_time,
    extension=".html",
    directory=rdir["workflow"],
)
logging.shutdown()
save_workflow_log(wf_log_file.storage_path, log_file_html.storage_path, workflow_name)
layout.single_layout(rdir["workflow"], [log_file_html])
