#!/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

__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

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 lal import LIGOTimeGPS

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 = 10, 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.")

	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.p_astro_topic = f'gstlal.{self.tag}.p_astro'

		# 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])
		)
			
		# 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(options.pastro_model_file)

		# 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,
		})

	def handle(self):
		# 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['coinc'])

				# 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 calculate_pastro(self, coinc):
		pa = None
		data = self.parse_data_from_coinc(coinc)
		if data:
			pa = self.model(data)
		return pa

	def parse_data_from_coinc(self, coinc):
		data = {}
		try:
			mchirp = lsctables.CoincInspiralTable.get_table(coinc).getColumnByName("mchirp")[0]
			snr = lsctables.CoincInspiralTable.get_table(coinc).getColumnByName("snr")[0]
			likelihood = lsctables.CoincTable.get_table(coinc).getColumnByName("likelihood")[0]
			template_id = lsctables.SnglInspiralTable.get_table(coinc).getColumnByName("Gamma0")[0]
		except Exception as e:
			logging.warning(f'Failed to parse coinc file. Error: {e}')

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

	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()
