#!/usr/bin/env python3

"""
Created on 29 Jun 2021

@author: Bruno Beloff (bruno.beloff@southcoastscience.com)

DESCRIPTION
The alert_status utility is used to report on the alerts generated by a specific alert specification. Alert causes are:

* L - Below lower threshold
* U - Above upper threshold
* N - Null value

SYNOPSIS
alert_status.py { -l | -d [-c CAUSE] } [-i INDENT] [-v] ID

EXAMPLES
alert_status.py -d -cL 123

DOCUMENT EXAMPLE
{"id": 77, "rec": "2021-09-07T11:40:00Z", "cause": null, "val": 589.6}

SEE ALSO
scs_analysis/alert
scs_analysis/monitor_auth
"""

import requests
import sys

from scs_analysis.cmd.cmd_alert_status import CmdAlertStatus

from scs_core.aws.client.monitor_auth import MonitorAuth
from scs_core.aws.manager.alert_status_finder import AlertStatusFinder

from scs_core.data.json import JSONify
from scs_core.data.datetime import LocalizedDatetime

from scs_core.sys.http_exception import HTTPException
from scs_core.sys.logging import Logging

from scs_host.sys.host import Host


# --------------------------------------------------------------------------------------------------------------------

if __name__ == '__main__':

    logger = None
    auth = None
    response = None
    report = None

    try:
        # ------------------------------------------------------------------------------------------------------------
        # cmd...

        cmd = CmdAlertStatus()

        if not cmd.is_valid():
            cmd.print_help(sys.stderr)
            exit(2)

        Logging.config('alert_status', verbose=cmd.verbose)
        logger = Logging.getLogger()

        logger.info(cmd)


        # ------------------------------------------------------------------------------------------------------------
        # resources...

        if not MonitorAuth.exists(Host):
            logger.error('MonitorAuth not available.')
            exit(1)

        try:
            auth = MonitorAuth.load(Host, encryption_key=MonitorAuth.password_from_user())
        except (KeyError, ValueError):
            logger.error('incorrect password.')
            exit(1)

        finder = AlertStatusFinder(requests, auth)
        logger.info(finder)


        # ------------------------------------------------------------------------------------------------------------
        # run...

        if cmd.latest:
            response = finder.find(cmd.id, None, cmd.response_mode())
            report = response.alert_statuses[0] if response.alert_statuses else None

        if cmd.history:
            response = finder.find(cmd.id, cmd.cause, cmd.response_mode())
            report = sorted(response.alert_statuses)

        # report...
        if report is not None:
            print(JSONify.dumps(report, indent=cmd.indent))

        if cmd.history:
            logger.info('retrieved: %s' % len(response.alert_statuses))


    except KeyboardInterrupt:
        print(file=sys.stderr)

    except HTTPException as ex:
        now = LocalizedDatetime.now().utc().as_iso8601()
        logger.error("%s: HTTP response: %s (%s) %s" % (now, ex.status, ex.reason, ex.data))
        exit(1)
