#!/usr/bin/env python

# Copyright (C) 2016 Ian W. Harry, Y Ddraig Goch
#
# 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
# in the knowledge that it will probably not be useful, and you'll moan at me,
# 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.

"""
Workflow generator to create diagnosis plots and figures of merit for an input
template bank.
"""

import argparse
import os
import shutil

import igwn_segments as segments

import pycbc.version
import pycbc.workflow as wf
from pycbc import add_common_pycbc_options, init_logging
from pycbc.results import layout
from pycbc.workflow import setup_splittable_dax_generated
from pycbc.workflow.jobsetup import (
    LalappsInspinjExecutable,
    PycbcCreateInjectionsExecutable,
    int_gps_time_to_str,
    select_generic_executable,
)

# Boiler-plate stuff
__author__ = "Ian Harry <ian.harry@ligo.org>"
__version__ = pycbc.version.git_verbose_msg
__date__ = pycbc.version.date
__program__ = "pycbc_make_bank_verifier_workflow"


# Some new executable classes. These can be moved into modules if needed
class BanksimExecutable(wf.Executable):
    """Class for running pycbc_banksim"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.ALL_TRIGGERS

    def create_node(self, analysis_time, inj_file, bank_file, extra_tags=None):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_opt("--signal-file", inj_file)
        node.add_input_opt("--template-file", bank_file)
        node.new_output_file_opt(
            analysis_time, ".dat", "--match-file", tags=self.tags + extra_tags
        )
        return node


class BanksimBankCombineExecutable(wf.Executable):
    """Class for running pycbc_banksim_combine_banks"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.ALL_TRIGGERS

    def create_node(self, analysis_time, inp_files, extra_tags=None):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_list_opt("--input-files", inp_files)
        node.new_output_file_opt(
            analysis_time, ".dat", "--output-file", tags=self.tags + extra_tags
        )
        return node


class BanksimMatchCombineExecutable(wf.Executable):
    """Class for running pycbc_banksim_match_combine"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.FINAL_RESULT

    file_input_options = [*wf.Executable.file_input_options, "--filter-func-file"]

    def create_node(
        self, analysis_time, match_files, inj_files, bank_files, extra_tags=None
    ):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_list_opt("--match-files", match_files)
        for curr_file in inj_files:
            node._add_input(curr_file)
        for curr_file in bank_files:
            node._add_input(curr_file)
        node.new_output_file_opt(
            analysis_time, ".h5", "--output-file", tags=self.tags + extra_tags
        )
        return node


class BanksimPlotFittingFactorsExecutable(wf.Executable):
    """Class for running pycbc_banksim_plot_fitting_factors"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.FINAL_RESULT

    def create_node(self, analysis_time, input_file, extra_tags=None):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_opt("--input-file", input_file)
        node.new_output_file_opt(
            analysis_time, ".png", "--output-file", tags=self.tags + extra_tags
        )
        return node


class BanksimPlotEffFittingFactorsExecutable(wf.Executable):
    """Class for running pycbc_banksim_plot_eff_fitting_factor"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.FINAL_RESULT

    def create_node(self, analysis_time, input_files, extra_tags=None):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_list_opt("--input-files", input_files)
        node.new_output_file_opt(
            analysis_time, ".png", "--output-file", tags=self.tags + extra_tags
        )
        return node


class BanksimTablePointInjsExecutable(wf.Executable):
    """Class for running pycbc_banksim_table_point_injs"""

    # This can be altered if you don't always want to store output files
    current_retention_level = wf.Executable.FINAL_RESULT

    def create_node(self, analysis_time, input_files, relative_dirs, extra_tags=None):
        if extra_tags is None:
            extra_tags = []
        node = wf.Executable.create_node(self)
        node.add_input_list_opt("--input-files", input_files)
        node.add_list_opt("--directory-links", relative_dirs)
        node.new_output_file_opt(
            analysis_time, ".html", "--output-file", tags=self.tags + extra_tags
        )
        return node


# Argument parsing and setup of workflow

# Use the standard workflow command-line parsing routines. Things like a
# configuration file are specified within the "workflow command line group"
# so run this with --help to see what options are added.
_desc = __doc__[1:]
parser = argparse.ArgumentParser(description=_desc)
add_common_pycbc_options(parser)
wf.add_workflow_command_line_group(parser)
wf.add_workflow_settings_cli(parser)
args = parser.parse_args()

init_logging(args.verbose)

# FIXME: opts.tags is currently unused here.

# Create the workflow object
workflow = wf.Workflow(args)

wf.makedir(args.output_dir)
os.chdir(args.output_dir)
args.output_dir = "."

rdir = layout.SectionNumber(
    "results", ["point_injection_sets", "broad_injection_sets", "workflow"]
)
wf.makedir(rdir.base)
wf.makedir(rdir["workflow"])
# Save config file to results directory
conf_dir = rdir["workflow/configuration"]
wf.makedir(conf_dir)
conf_path = os.path.join(conf_dir, "configuration.ini")
with open(conf_path, "w") as conf_fh:
    workflow.cp.write(conf_fh)
conf_file = wf.FileList(
    [wf.File(workflow.ifos, "", workflow.analysis_time, file_url="file://" + conf_path)]
)

# Input bank file
file_attrs = {
    "segs": workflow.analysis_time,
    "tags": [],
    "ifo_list": workflow.ifos,
    "description": "TEMPLATEBANK",
}
inp_bank = workflow.cp.get("workflow", "input-bank")
inp_bank = wf.resolve_url_to_file(inp_bank, attrs=file_attrs)

# Inspinj Executable
inspinj_exe = select_generic_executable(workflow, "injection")
# The output must be in xml format for pycbc_split_inspinj to work,
# while h5 will work when splitting with pycbc_hdf5_splitbank
splitter = workflow.cp.get("executables", "splitinj")
inspinj_exe.extension = ".xml" if "pycbc_split_inspinj" in splitter else ".h5"
# The following line is redundant for lalapps_inspinj, but not
# for pycbc_create_injections
inspinj_exe.current_retention_level = wf.Executable.FINAL_RESULT

# Inspinj job
inspinj_job = inspinj_exe(
    workflow.cp, "injection", out_dir=".", ifos=workflow.ifos, tags=[]
)


def add_banksim_set(workflow, file_tag, num_injs, curr_tags, split_banks):
    """Add a group of jobs that does a complete banksim."""
    t_seg = segments.segment([1000000000, 1000000000 + int(num_injs)])
    inspinj_job.update_current_tags(curr_tags)
    if inspinj_exe is LalappsInspinjExecutable:
        node = inspinj_job.create_node(t_seg)
        inj_file = node.output_file
    elif inspinj_exe is PycbcCreateInjectionsExecutable:
        # Ensure pycbc_create_injections dedicated configuration files
        # are copied over to the results directory
        shutil.copy2(inspinj_job.get_opt("config-files"), conf_dir)
        node, inj_file = inspinj_job.create_node()
        node.add_opt("--gps-start-time", int_gps_time_to_str(t_seg[0]))
        node.add_opt("--gps-end-time", int_gps_time_to_str(t_seg[1]))
    else:
        raise NotImplementedError
    workflow += node
    # Here we apply the em-bright criterion
    if workflow.cp.has_option("workflow-injections", "em-bright-only"):
        # Job to carry on with em-bright injections only
        em_filter_exe = select_generic_executable(workflow, "em_bright_filter")
        em_filter_job = em_filter_exe(
            workflow.cp,
            "em_bright_filter",
            out_dir=".",
            ifos=workflow.ifos,
            tags=curr_tags,
        )
        node = em_filter_job.create_node(inj_file, t_seg, curr_tags)
        workflow += node
        inj_file = node.output_files[0]

    split_injs = setup_splittable_dax_generated(
        workflow, [inj_file], "splitinjfiles", curr_tags
    )
    # Banksim job
    banksim_job = BanksimExecutable(
        workflow.cp,
        "banksim",
        out_dir=file_tag + "match",
        ifos=workflow.ifos,
        tags=[file_tag],
    )
    bscombine_job = BanksimBankCombineExecutable(
        workflow.cp,
        "banksim_bank_combine",
        out_dir=file_tag + "match",
        ifos=workflow.ifos,
        tags=[file_tag],
    )
    mcombine_job = BanksimMatchCombineExecutable(
        workflow.cp,
        "banksim_match_combine",
        out_dir=file_tag + "match",
        ifos=workflow.ifos,
        tags=[file_tag],
    )
    banksim_files = wf.FileList([])

    for inj_idx, split_inj in enumerate(split_injs):
        inj_tag = f"INJ{inj_idx}"
        currinj_banksim_files = wf.FileList([])
        for bank_idx, split_bank in enumerate(split_banks):
            bank_tag = f"BANK{bank_idx}"
            inj_tag = f"INJ{inj_idx}"
            node = banksim_job.create_node(
                workflow.analysis_time,
                split_inj,
                split_bank,
                extra_tags=[bank_tag, inj_tag],
            )
            workflow += node
            currinj_banksim_files.append(node.output_file)
        curr_node = bscombine_job.create_node(
            workflow.analysis_time, currinj_banksim_files, extra_tags=[inj_tag]
        )
        workflow += curr_node
        banksim_files.append(curr_node.output_file)
    curr_node = mcombine_job.create_node(
        workflow.analysis_time, banksim_files, split_injs, split_banks
    )
    workflow += curr_node
    return curr_node.output_file


# Set up the actual banksims
curr_tags = ["shortinjbanksplit"]
split_banks = setup_splittable_dax_generated(
    workflow, [inp_bank], "splitbankfiles", curr_tags
)

output_pointinjs = {}
for file_tag, num_injs in workflow.cp.items("workflow-pointinjs"):
    curr_tags = ["shortinjs", file_tag]
    curr_file = add_banksim_set(workflow, file_tag, num_injs, curr_tags, split_banks)
    output_pointinjs[file_tag] = curr_file

curr_tags = ["broadinjbanksplit"]
split_banks = setup_splittable_dax_generated(
    workflow, [inp_bank], "splitbankfiles", curr_tags
)

output_broadinjs = {}
for file_tag, num_injs in workflow.cp.items("workflow-broadinjs"):
    curr_tags = ["broadinjs", file_tag]
    curr_file = add_banksim_set(workflow, file_tag, num_injs, curr_tags, split_banks)
    output_broadinjs[file_tag] = curr_file

plotting_nodes = []

out_dir = rdir.base
point_injs_table_exe = BanksimTablePointInjsExecutable(
    workflow.cp,
    "banksim_table_point_injs",
    out_dir=rdir["point_injection_sets"],
    ifos=workflow.ifos,
)
eff_fitting_facs_exe = BanksimPlotEffFittingFactorsExecutable(
    workflow.cp, "banksim_plot_eff_fitting_fac", out_dir=out_dir, ifos=workflow.ifos
)
plot_fitting_facs_exe = BanksimPlotFittingFactorsExecutable(
    workflow.cp,
    "banksim_plot_fitting_factors",
    out_dir=rdir["point_injection_sets"],
    ifos=workflow.ifos,
)

summary_page_files = []
# Add files to point_inj_summ_files in pairs. A tuple of one entry will span
# the full column. A pair exists together.
point_inj_summ_files = []
# Nothing in this yet, so not sure how to set this.
broad_inj_summ_files = []

# Set the point injection names
for f in sorted(output_pointinjs):
    rdir[f"point_injection_sets/{f}"]

curr_node = point_injs_table_exe.create_node(
    workflow.analysis_time,
    [output_pointinjs[f] for f in sorted(output_pointinjs)],
    ["../" + rdir.name[f"point_injection_sets/{f}"] for f in sorted(output_pointinjs)],
)
workflow += curr_node
plotting_nodes.append(curr_node)
point_inj_summ_files.append((curr_node.output_file,))

secs = workflow.cp.get_subsections("banksim_plot_eff_fitting_fac")
for tag in secs:
    eff_fitting_facs_exe.update_current_tags([tag])
    curr_node = eff_fitting_facs_exe.create_node(
        workflow.analysis_time, [output_pointinjs[f] for f in output_pointinjs]
    )
    workflow += curr_node
    plotting_nodes.append(curr_node)
    summary_page_files.append(curr_node.output_file)

# Set up layouts
layout.group_layout(rdir.base, summary_page_files)
layout.two_column_layout(rdir["point_injection_sets"], point_inj_summ_files)
# Also add broad_injs when ready

secs = workflow.cp.get_subsections("banksim_plot_fitting_factors")
# Note a sorted(dict) returns a list of sorted *keys*. Works in python 2.4+
# and python 3 (dict.keys is removed in python 3)
for tag in sorted(output_broadinjs):
    curr_outs = []
    curr_file = output_broadinjs[tag]
    plot_fitting_facs_exe.update_output_directory(rdir[f"broad_injection_sets/{tag}"])
    for tag2 in secs:
        plot_fitting_facs_exe.update_current_tags([tag, tag2])
        curr_node = plot_fitting_facs_exe.create_node(workflow.analysis_time, curr_file)
        workflow += curr_node
        plotting_nodes.append(curr_node)
        curr_outs.append((curr_node.output_file,))
    # Other outputs could go here, before running the layout
    layout.two_column_layout(rdir[f"broad_injection_sets/{tag}"], curr_outs)

for tag in sorted(output_pointinjs):
    curr_outs = []
    curr_file = output_pointinjs[tag]
    plot_fitting_facs_exe.update_output_directory(rdir[f"point_injection_sets/{tag}"])
    for tag2 in secs:
        plot_fitting_facs_exe.update_current_tags([tag, tag2])
        curr_node = plot_fitting_facs_exe.create_node(workflow.analysis_time, curr_file)
        workflow += curr_node
        plotting_nodes.append(curr_node)
        curr_outs.append((curr_node.output_file,))
    # Other outputs could go here, before running the layout
    layout.two_column_layout(rdir[f"point_injection_sets/{tag}"], curr_outs)

# Save config file(s) to results directory
layout.single_layout(conf_dir, conf_file)

# Create versioning information
wf.make_versioning_page(
    workflow,
    workflow.cp,
    rdir["workflow/version"],
)


wf.make_results_web_page(
    workflow, os.path.join(os.getcwd(), rdir.base), explicit_dependencies=plotting_nodes
)

workflow.save()
