#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python

__usage__ = "gstlal_ll_inspiral_pastro_uploader [--options]"
__description__ = "an executable to calculate p(astro) values and upload to GraceDB events"
__author__ = "Rebecca Ewing (rebecca.ewing@ligo.org)"

#-------------------------------------------------
#				   Preamble
#-------------------------------------------------

from collections import deque, OrderedDict
import http.client as httplib
import json
import logging
from optparse import OptionParser
import time
import copy
from io import BytesIO
import tempfile
import shutil
import os

from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from ligo.lw import lsctables

import numpy

from ligo.gracedb.rest import GraceDb, HTTPError
from ligo.gracedb.rest import DEFAULT_SERVICE_URL as DEFAULT_GRACEDB_URL
from ligo.scald import utils

from gstlal import events
from gstlal import inspiral

from pastro import pastro

class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass

lsctables.use_in(LIGOLWContentHandler)

#-------------------------------------------------
#				   Functions
#-------------------------------------------------

def parse_command_line():

	parser = OptionParser(usage=__usage__, description=__description__)
	parser.add_option("-v", "--verbose", default=False, action="store_true", help = "Be verbose.")
	parser.add_option("--num-messages", type = int, default = 10000, help="number of messages to process per cadence")
	parser.add_option("--tag", metavar = "string", default = "test", help = "Sets the name of the tag used. Default = 'test'")
	parser.add_option("--processing-cadence", type = "float", default = 0.1, help = "Rate at which the event uploader acquires and processes data. Default = 0.1 seconds.")
	parser.add_option("--request-timeout", type = "float", default = 0.2, help = "Timeout for requesting messages from a topic. Default = 0.2 seconds.")
	parser.add_option("--kafka-server", metavar = "string", help = "Sets the server url that the kafka topic is hosted on. Required.")
	parser.add_option("--input-topic", metavar = "string", action="append", help = "Sets the input kafka topic(s). Required.")
	parser.add_option("--gracedb-service-url", metavar = "url", default = DEFAULT_GRACEDB_URL, help = "Override default GracedB service url (optional, default is {}).".format(DEFAULT_GRACEDB_URL))
	parser.add_option("--pastro-filename", metavar = "string", default = "p_astro.json", help = "Name to upload the p(astro) file with. Default is p_astro.json.")
	parser.add_option("--model-name", metavar = "string", help = "Name of pastro model used, eg FGMC.")
	parser.add_option("--pastro-model-file", metavar = "file", help = "Filename of pastro model.")
	parser.add_option("--update-model-cadence", metavar = "seconds", type = "float", default = 4. * 3600., help = "Cadence on which to update the model file with latest ranking statistic information. Default is four hours.")
	parser.add_option("--rank-stat", metavar = "file", help = "Filename of ranking stat pdf to update the pastro model with.")

	options, args = parser.parse_args()

	return options, args

#-------------------------------------------------
#					Classes
#-------------------------------------------------

class PAstroUploader(events.EventProcessor):
	def __init__(self, options):
		logging.info('setting up pastro uploader...')

		self.tag = options.tag
		self.model_name = options.model_name
		self.max_retries = 3
		self.filename = options.pastro_filename
		self.pastro_model_file = options.pastro_model_file
		self.p_astro_topic = f'gstlal.{self.tag}.p_astro'

		self.rank_stat = options.rank_stat
		self.last_rankstat_update = None
		self.update_rankstat_cadence = options.update_model_cadence

		self.is_injection_job = (options.input_topic[0] == 'inj_uploads')
		heartbeat_topic = f"gstlal.{options.tag}.pastro_uploader_heartbeat" if not self.is_injection_job else f"gstlal.{options.tag}.inj_pastro_uploader_heartbeat"

		# init the EventProcessor
		events.EventProcessor.__init__(
			self,
			process_cadence=options.processing_cadence,
			request_timeout=options.request_timeout,
			num_messages=options.num_messages,
			kafka_server=options.kafka_server,
			input_topic=[f"gstlal.{options.tag}.{topic}" for topic in options.input_topic],
			tag='-'.join([self.tag, self.model_name]),
			send_heartbeats = True,
			heartbeat_cadence = 60.,
			heartbeat_topic = heartbeat_topic,
		)
		
		# set up gracedb client
		if options.gracedb_service_url.startswith("file"):
			self.client = inspiral.FakeGracedbClient(options.gracedb_service_url)
		else:
			self.client = GraceDb(options.gracedb_service_url)

		# load model file
		self.model = self.load_model(self.pastro_model_file)
		# attempt to initialize model with ranking stat info
		self.add_rankstat_to_model()

		# start a list of events
		self.events = deque(maxlen=100)

	def ingest(self, message):
		# load the message value
		msg = json.loads(message.value())

		# append to list of messages to be handled
		# these messages come post aggregation, so
		# we will calculate a pastro for each one
		# without checking for duplicates
		self.events.append({
			'gid': msg['gid'],
			'time': msg['time'],
			'time_ns': msg['time_ns'],
			'coinc': self.load_xmlobj(msg['coinc']),
			'upload_attempts': 0,
		})

		# update pastro model with ranking stat info
		t = inspiral.now()
		if not self.last_rankstat_update or t - self.last_rankstat_update >= self.update_rankstat_cadence:
			self.add_rankstat_to_model()

	def handle(self):
		# if we have not updated the model with
		# ranking stat info yet, we cant
		# accurately compute pastros. Check that
		# this is done before continuing.
		if not self.last_rankstat_update:
			return

		# for all events in the list, calculate
		# the pastro and upload to GraceDB
		for event in copy.copy(self.events):
			logging.debug(f'Processing {event["gid"]}...')
			if event['upload_attempts'] < self.max_retries:
				pastro = self.calculate_pastro(event)

				# attempt to upload the file
				response = self.upload_file(
					event['gid'],
					"GstLAL internally computed p-astro",
					self.filename,
					pastro,
					f"{self.model_name}_p_astro"
				)

				# after successful upload, add label
				if response:
					try:
						response = self.client.writeLabel(event['gid'], 'PASTRO_READY')
					except HTTPError as error:
						logging.warning(error)
					else:
						# remove this event from the list
						logging.debug(f'Successfully uploaded {self.filename} to {event["gid"]}.')
						self.events.remove(event)
						self.send_p_astro(event, pastro)
				else:
					logging.debug(f'Failed to upload {self.filename} to {event["gid"]}.')
					event['upload_attempts'] += 1

			# remove events after exceeding retries
			else:
				logging.warning(f'Exceeded {self.max_retries} attempts to upload pastro file for {event["gid"]}. Removing this event from deque.')
				self.events.remove(event)

	def load_xmlobj(self, xmlobj):
		if isinstance(xmlobj, str):
			xmlobj = BytesIO(xmlobj.encode("utf-8"))
		return ligolw_utils.load_fileobj(xmlobj, contenthandler = LIGOLWContentHandler)

	def load_model(self, filename):
		model = pastro.load(filename)	
		model.finalize(model.prior())
		return model

	def add_rankstat_to_model(self):
		# update the pastro model with ranking stat information
		# from the current analysis in the path provided by 
		# self.rank_stat. Note: this will fail if the analysis 
		# hasnt burned in yet, since there wont be a ranking stat
		# pdf file yet. Hence the try/except with OSError
		try:
			self.model.update_rankstatpdf(self.rank_stat)
			self.model.finalize(self.model.prior())

			tmp, tmp_path = tempfile.mkstemp(".h5", dir=os.getenv("_CONDOR_SCRATCH_DIR", tempfile.gettempdir()))

			logging.debug(f'Writing model to {tmp_path}...')
			self.model.to_h5(tmp_path)

			logging.debug(f'Moving {tmp_path} to {self.pastro_model_file}...')
			shutil.move(tmp_path, self.pastro_model_file)

			self.last_rankstat_update = inspiral.now()

		except OSError as error:
			logging.warning(f"Failed to update model with ranking stat info: {error}")

		return

	def calculate_pastro(self, event):
		pa = None
		data = self.parse_data_from_coinc(event['coinc'])
		if data:
			pa = self.model(data,inj=self.is_injection_job)
		return pa

	def parse_data_from_coinc(self, coinc):
		try:
			coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(coinc)
			coinc_event_table = lsctables.CoincTable.get_table(coinc)
			sngl_table = lsctables.SnglInspiralTable.get_table(coinc)
		except ValueError:
			logging.warning(f'ValueError: Failed to parse tables from coinc file.')
		try:
			coinc_inspiral_row = coinc_inspiral_table[0]
			coinc_event_row = coinc_event_table[0]
			sngl_row = sngl_table[0]
		except IndexError:
			logging.warning(f'IndexError: Table does not have a row.')
		try:
			mchirp = coinc_inspiral_row.mchirp
			snr = coinc_inspiral_row.snr
			likelihood = coinc_event_row.likelihood
			template_id = sngl_row.template_id
			fhigh = sngl_row.f_final
		except AttributeError:
			logging.warning(f'Row does not have a column named asked for')

		else:
			return {
				'mchirp': mchirp,
				'likelihood': likelihood,
				'template_id': template_id,
				'snr': snr,
				'fhigh': fhigh
			}

	def upload_file(self, graceid, message, filename, contents, tag, retries = 3):
		for attempt in range(retries):
			try:
				# try to upload the file
				response = self.client.writeLog(
					graceid,
					message,
					filename = filename,
					filecontents = contents,
					tagname = tag
				)
			except HTTPError as error:
				# if the upload fails with an HTTPError, print it out
				logging.warning(error)
			else:
				# if the upload does not fail check that the
				# response is what we want and leave this function
				if response.status == httplib.CREATED:
					return response

			# if this upload attempt failed print a message, sleep for
			# 1 second before trying again
			logging.info(f'upload of {filename} for {graceid} failed on attempt {attempt} / {retries}')
			time.sleep(1.)

		else:
			# if all uploads failed, return False
			logging.warning(f'upload of {filename} for {graceid} failed.')
			return False


	def send_p_astro(self, event, pastro):
		"""
		send p(astro) via Kafka
		"""
		p_astro = {
			'time': event['time'],
			'time_ns': event['time'],
			'p_astro': pastro
		}
		self.producer.produce(topic=self.p_astro_topic, value=json.dumps(pastro))
		self.producer.poll(0)



#-------------------------------------------------
#					 Main
#-------------------------------------------------

if __name__ == '__main__':
	# parse arguments
	options, args = parse_command_line()

	# set up logging
	log_level = logging.DEBUG if options.verbose else logging.INFO
	logging.basicConfig(format = '%(asctime)s | event_uploader : %(levelname)s : %(message)s')
	logging.getLogger().setLevel(log_level)

	# create event uploader instance
	pastro_uploader = PAstroUploader(options)

	# start up
	pastro_uploader.start()
