#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1674814439023/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2020  Patrick Godwin (patrick.godwin@ligo.org)
#
# 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 2 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 os
import sys

from gstlal.config.inspiral import Config
from gstlal.dags.inspiral import DAG
from gstlal.datafind import DataCache, DataType
from gstlal.workflows import write_makefile


# set up command line options
parser = argparse.ArgumentParser()

subparser = parser.add_subparsers(title="commands", metavar="<command>", dest="command")
subparser.required = True

p = subparser.add_parser("init", help="generate a Makefile based on configuration")
p.add_argument("-c", "--config", help="Sets the path to read configuration from.")
p.add_argument("-f", "--force", action="store_true", help="If set, overwrites the existing Makefile")

p = subparser.add_parser("create", help="create a workflow DAG")
p.add_argument("-c", "--config", help="Sets the path to read configuration from.")
p.add_argument("-w", "--workflow", default="inspiral", help="Sets the type of workflow to run. Choose setup or inspiral.")


# load config
args = parser.parse_args()
config = Config.load(args.config)

# create makefile
if args.command == "init":
	if os.path.exists(os.path.join(os.getcwd(), "Makefile")) and not args.force:
		print("Makefile already exists. To overwrite, run with --force", file=sys.stderr)
	else:
		write_makefile(config, f"Makefile.online_inspiral_template", config_filename=args.config)

# generate dag
elif args.command == "create":
	# create dag
	config.setup()
	dag = DAG(config)
	dag.create_log_dir()

	if args.workflow == "setup":
		# input data products
		ref_psd = DataCache.from_files(DataType.REFERENCE_PSD, config.data.reference_psd)
		split_bank = DataCache.find(DataType.SPLIT_BANK, svd_bins="*", subtype="*")

		# generate dag layers
		svd_bank = dag.svd_bank(ref_psd, split_bank)
		if config.svd.checkerboard:
			svd_bank = dag.checkerboard(ref_psd, svd_bank)
		dist_stats = dag.create_prior(svd_bank, ref_psd)

	elif args.workflow == "inspiral":
		# input data products
		svd_banks = DataCache.find(DataType.SVD_BANK, root="filter", svd_bins="*")
		dist_stats = DataCache.find(DataType.DIST_STATS, svd_bins="*")

		zerolag_pdfs = DataCache.generate(
			DataType.ZEROLAG_DIST_STAT_PDFS,
			config.all_ifos,
			svd_bins=config.svd.bins,
		)
		marg_pdf = DataCache.generate(DataType.DIST_STAT_PDFS, config.all_ifos)

		# generate dag layers
		if config.filter.injections:
			dag.filter_injections_online(svd_banks, dist_stats, zerolag_pdfs, marg_pdf)
		dag.filter_online(svd_banks, dist_stats, zerolag_pdfs, marg_pdf)
		dag.marginalize_online(marg_pdf)
		dag.track_noise()
		if config.services.kafka_server:
			dag.count_events(dist_stats)
			dag.upload_events()
			dag.upload_pastro()
			dag.plot_events()
			dag.collect_metrics()
	else:
		raise ValueError('The workflow "%s" is not defined. Choose one from "setup" or "inspiral".' % args.workflow)

	# write dag/script to disk
	dag_name = f"online_{args.workflow}_dag"
	dag.write_dag(f"{dag_name}.dag")
	dag.write_script(f"{dag_name}.sh")

else:
	raise ValueError('The execute command "%s" is not defined. Choose one from "init" or "create".' % args.command)
