#!/usr/bin/env python
# encoding: utf-8
"""
*This is a template gocart plugin script. Duplicate this script, give it a name starting with 'gp_' (e.g. 'gp_slack_alert.py' and modifiy the code to do something magical everytime a GCN alert is read.*

:Author:
    David Young

:Date Created:
    May 11, 2023

Usage:
    gp_template <alertDir>

Options:
    alertDir              path to an alert directory

    -h, --help            show this help message
    -v, --version         show version
"""
################# GLOBAL IMPORTS ####################
import sys
import os
from fundamentals import tools


def plugin(
        log,
        settings,
        alertFiles,
        alertMeta):
    """*this is the gocart plugin function that will be run when an alert is read*

    **Key Arguments:**

    - ``log`` -- logger
    - ``settings`` -- these are the gocart settings, you can add extra settings to the gocart.yaml settings file and they will be read here.
    - ``alertFiles`` -- a list of all the files generated by gocart for the alert
    - ``alertMeta`` -- a dictionary of the alert metadata from the json alert, FITS Header and gocart generated extras.      
    """
    log.debug('starting the ``plugin`` function')

    alertType = alertMeta["ALERT"]["alert_type"]
    evertId = alertMeta["ALERT"]["superevent_id"]

    print(f"Here are the alert files generated from {alertType} alert of event {evertId}:")
    for f in alertFiles:
        print(f)

    log.debug('completed the ``plugin`` function')
    return None


# DO NOT EDIT ANYTHING BOTH THIS LINE
def main(arguments=None):
    """
    *The main function used when ``gp_template.py`` is run as a single script from the cl*
    """

    # SETUP THE COMMAND-LINE UTIL SETTINGS
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="gocart",
        defaultSettingsFile=True
    )
    arguments, settings, log, dbConn = su.setup()

    # UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
    # AUTOMATICALLY
    a = {}
    for arg, val in list(arguments.items()):
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        a[varname] = val
        if arg == "--dbConn":
            dbConn = val
            a["dbConn"] = val
        log.debug('%s = %s' % (varname, val,))

    # GENERATE A LIST OF FILE PATHS
    pathToDirectory = a["alertDir"]
    alertFiles = []
    alertMeta = None
    for d in os.listdir(pathToDirectory):
        filepath = os.path.join(pathToDirectory, d)
        if os.path.isfile(filepath) and d[0] != ".":
            alertFiles.append(d)

        if d == "meta.yaml":
            import yaml
            # ADD YAML CONTENT TO DICTIONARY
            with open(filepath, 'r') as stream:
                alertMeta = yaml.safe_load(stream)

    plugin(
        log=log,
        settings=settings,
        alertFiles=alertFiles,
        alertMeta=alertMeta
    )

    return


if __name__ == '__main__':
    main()
