#!/usr/bin/env python
# ==============================================================
#
#  Abs:   Script for comparing barcodes and standardize
#         parameters between EPICS and Oracle
#
#  Name:  mgnt_stdz_compare
#
#  Usage: mgnt_stdz_compare.py [-h] [--email RECIPIENT]
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Jul-2020, A. Le (anle)
# --------------------------------------------------------------
#  Mods: (Latest to oldest)
#     13-Jan-2023, A. Le (anle)
#         Move report status to end of subject line
#     04-Jan-2023, A. Le (anle)
#         Print email sender and recipient
#     15-Dec-2022, A. Le (anle)
#         Look at Stdz Func field in Oracle
#         Go to script directory before accessing templates
#         Print done message
#     13-Dec-2022, A. Le (anle)
#         Convert templates to Jinja
#         Add report status to email subject line
#     08-Dec-2022, A. Le (anle)
#         Reformat code
#         Add docstrings
#     06-Jun-2022, A. Le (anle)
#         Use cx_Oracle to get polynomial and additional data
#     31-May-2022, A. Le (anle)
#         Make code compatible with Python 2 and 3
#     19-Nov-2021, A. Le (anle)
#         Add facility argument
#     30-Sep-2021, A. Le (anle)
#         Suppress timeout messages
#     29-Sep-2021, A. Le (anle)
#         Add missing EPICS column
#     26-Aug-2021, A. Le (anle)
#         Avoid writing report to file for now
#         Add abbreviated options
#     23-Aug-2021, A. Le (anle)
#         Make script directory independent
#         Rename to mgnt_stdz_compare.py
#         Send report to user by default
#         Warn user if script is called from lcls-dev2 or lcls-dev3
#     13-Jul-2021, A. Le (anle)
#         Run caget_many once for all pvs
#         Add multithreading for pvcall
#     31-Aug-2020, A. Le (anle)
#         Clean up code
#     13-Aug-2020, A. Le (anle)
#         Add switch to send to different email
#     11-Aug-2020, A. Le (anle)
#         Adjust formatting
#         Use pyepics for caget
#         Add "not installed" column
#     27-Jul-2020, A. Le (anle)
#         Add logic for STDZDISABLE
#         Report total deferred and non-deferred magnets
#         -Add space between fail and missing sections
#         -Add message before stats table
#     17-Jul-2020, A. Le (anle)
#         Rename variables
#     15-Jul-2020, A. Le (anle)
#         Mark differing coefficients
#         Move templates to separate directory
#         Use IVB instead of POLYCOEF
#     14-Jul-2020, A. Le (anle)
#         Group devices by area
#         Report devices missing by area
#         Add table of missing magnets
#     13-Jul-2020, A. Le (anle)
#         Fix caget output
#         List device name and operational status
#     09-Jul-2020, A. Le (anle)
#         Take magnets from Oracle Infrastructure database
#
# ==============================================================
#
from __future__ import print_function

import argparse
import json
import os
import pwd
import smtplib
import socket
from collections import Counter, OrderedDict, defaultdict
from datetime import datetime
from email.mime.text import MIMEText
from enum import Enum
from itertools import product

import epics
from jinja2 import Environment, FileSystemLoader

from mgnt_get_elements import get_all_magnets

COLS = [('BARCODE', 'BARCODE', 'Barcode'), ('STDZCYCLENUM', 'STDZCYCLENUM_VAL', 'Stdzcyclenum'),
        ('TRIMRAMPRATE', 'TRIMRAMPRATE_VAL', 'Trimramprate'), ('TRIMSETL', 'TRIMSETL_VAL', 'Trimsetl'),
        ('STDZDISABLE', 'STDZ_FUNC', '')]


class Status(Enum):
    """Enumerates status codes for barcode and standardize parameter comparison."""

    NOT_IN_EPICS = 1
    """The barcode and standardize parameters are missing from EPICS."""

    NOT_IN_ORACLE = 2
    """The barcode and standardize parameters are missing from Oracle."""

    NOT_MATCHING = 3
    """The EPICS and Oracle barcode and standardize parameters do not match."""

    MATCHING = 4
    """The EPICS and Oracle barcode and standardize parameters match."""


def get_all_stdz_info(devices, fields):
    """Gets barcode and standardize parameters for all magnets from EPICS.

    Args:
        devices (list[tuple]): Polynomial data for all magnets retrieved from Oracle.
        fields (list[str]): PV fields related to barcode and standardize.

    Returns:
        defaultdict[str, dict[str, Any]]: A dict mapping device names to dicts of PV fields and EPICS values related to
            barcode and standardize.
    """
    stdz_info_dict = defaultdict(dict)
    pvs = ['{}:{}'.format(device[3], field) for device, field in product(devices, fields)]
    stdz_info = epics.caget_many(pvs, timeout=5)
    for (device, field), inf in zip(product(devices, fields), stdz_info):
        stdz_info_dict[device[3]][field] = inf

    return stdz_info_dict


def get_oracle_stdz_info(devices):
    """Gets barcode and standardize parameters for all magnets from Oracle.

    Args:
        devices (list[tuple]): Polynomial data for all magnets retrieved from Oracle.

    Returns:
        defaultdict[str, dict[str, Any]]: A dict mapping device names to dicts of PV fields and Oracle values related to
            barcode and standardize.
    """
    stdz_info_dict = {}
    for device in devices:
        stdz_info_dict[device[3]] = {
            'TRIMSETL_VAL': device[30],
            'BARCODE': device[1],
            'STDZCYCLENUM_VAL': device[25],
            'TRIMRAMPRATE_VAL': device[29],
            'STDZ_FUNC': device[24]
        }

    return stdz_info_dict


def process_epics_stdz_info(ca_name, pvs, stdz_info_dict):
    """Gets barcode and standardize parameters for one magnet from EPICS.

    Args:
        ca_name (str): The device name of the magnet.
        pvs (list[str]): PV fields related to barcode and standardize.
        stdz_info_dict (defaultdict[str, dict[str, Any]]): A dict mapping device names to dicts of PV fields and EPICS
            values related to barcode and standardize.

    Returns:
        tuple: A tuple containing:

        - list: Values from EPICS related to barcode and standardize.
        - bool | Status: True if barcode and standardize parameters were found for the given device name,
          Status.NOT_IN_EPICS otherwise.
    """
    inf = [stdz_info_dict[ca_name][pv] for pv in pvs]
    if None in inf:
        return [], Status.NOT_IN_EPICS

    return inf, True


def process_oracle_stdz_info(ca_name, labels, stdz_info_dict):
    """Gets barcode and standardize parameters for one magnet from Oracle.

    Args:
        ca_name (str): The device name of the magnet.
        pvs (list[str]): PV fields related to barcode and standardize.
        stdz_info_dict (defaultdict[str, dict[str, Any]]): A dict mapping device names to dicts of PV fields and Oracle
            values related to barcode and standardize.

    Returns:
        tuple: A tuple containing:

        - list: Values from Oracle related to barcode and standardize.
        - bool | Status: True if barcode and standardize parameters were found for the given device name,
          Status.NOT_IN_ORACLE otherwise.
    """
    inf = [stdz_info_dict[ca_name][label] for label in labels]
    if None in inf:
        return [], Status.NOT_IN_ORACLE

    return inf, True


def compare_dev_pvs(device, cols, stdz_info_dict, oracle_stdz_info):
    """Checks whether the barcode and standardize parameters from EPICS and Oracle match for a magnet.

    Args:
        device (str): The device name of the magnet.
        cols (list[tuple]): The columns representing barcode/standardize parameters, each as a tuple containing:

        - str: The EPICS PV fields.
        - str: The Oracle fields.
        - str: The column label.

        poly_dict (dict[str, numpy.ndarray]): The dict containing device names and their corresponding polynomials.
        oracle_poly (_type_): The polynomial coefficients from Oracle.

    Returns:
        tuple: A tuple containing:

        - list[Any]: The barcode and standardize parameters from Oracle.
        - list[Any]: The barcode and standardize parameters from EPICS.
        - Status: Whether the both sets of parameters match or one of them is missing.
    """
    pvs = [col[0] for col in cols]
    labels = [col[1] for col in cols]
    ca_vals, ca_status = process_epics_stdz_info(device, pvs, stdz_info_dict)
    oracle_vals, oracle_status = process_oracle_stdz_info(device, labels, oracle_stdz_info)
    if ca_status != Status.NOT_IN_EPICS and oracle_status != Status.NOT_IN_ORACLE:
        oracle_stdzenable = oracle_vals[-1]
        where_matching, status = mark_matching(ca_vals[:-1], oracle_vals[:-1], oracle_stdzenable)
    elif oracle_status == Status.NOT_IN_ORACLE:
        where_matching = [False] * len(cols[:-1])
        status = oracle_status
    else:
        where_matching = [False] * len(cols[:-1])
        status = ca_status

    return oracle_vals, ca_vals, where_matching, status


def mark_matching(ca_vals, oracle_vals, oracle_stdzenable):
    """Compares a magnet's barcode and standardize parameters between Oracle and EPICS.

    Args:
        ca_vals (list[Any]): The barcode and standardize parameters from EPICS.
        oracle_vals (list[Any]): The barcode and standardize parameters from Oracle.
        oracle_stdzenable (bool): True if standardize is enabled for the magnet according to Oracle, False otherwise.

    Returns:
        tuple: A tuple containing:

        - list[bool]: Whether the Oracle and EPICS values of each paramater match.
        - Status: Status.MATCHING if all parameters match, Status.NOT_MATCHING otherwise.
    """
    oracle_ca_match = [is_matching(c, o) for c, o in zip(ca_vals, oracle_vals)]
    if oracle_stdzenable == 'DISABLED':
        oracle_ca_match[1] = True

    if all(oracle_ca_match):
        status = Status.MATCHING
    else:
        status = Status.NOT_MATCHING

    return oracle_ca_match, status


def is_matching(a, b):
    """Converts two values to float if possible and returns True if they are equal, False otherwise."""
    try:
        if type(a) in (int, float) and type(b) in (int, float):
            return float(a) == float(b)

        return a == b
    except ValueError:
        return a == b


def create_stats_table(areas, area_counts, pass_counts, fail_counts, missing_oracle_counts, missing_epics_counts,
                       not_installed_counts):
    """Generates an HTML table containing the number of barcode and standardize parameter inconsistencies for each area.

    Args:
        areas (OrderedDict[str, Any]): The magnet areas represented as an ordered set.
        area_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of magnets in
            each area, indexed by deferred status.
        pass_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of magnets in
            each area with matching barcode/standardize parameters in each area, indexed by deferred status.
        fail_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of magnets in
            each area with inconsistent barcode/standardize parameters in each area, indexed by deferred status.
        missing_oracle_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of
            magnets in each area with barcode/standardize parameters missing from Oracle, indexed by deferred status.
        missing_epics_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of
            magnets in each area with barcode/standardize parameters missing from Oracle, indexed by deferred status.
        not_installed_counts (defaultdict[bool, Counter[str]])): A dict containing a counter storing the number of
            magnets in each area that are not installed, indexed by deferred status.

    Returns:
        str: HTML code for a table containing the number of passing and failing magnets for each area.
    """
    # Create row for each area
    area_stats = ''
    for area in areas:
        area_stats += '<tr><th>{}</th>'.format(area)
        for counts in [
                area_counts, pass_counts, fail_counts, missing_oracle_counts, missing_epics_counts, not_installed_counts
        ]:
            area_stats += '<td>{}</td>'.format(counts[False][area] + counts[True][area])

        area_stats += '</tr>\n'

    total_def_stats = ''
    total_nondef_stats = ''
    total_stats = ''
    for counts in [
            area_counts, pass_counts, fail_counts, missing_oracle_counts, missing_epics_counts, not_installed_counts
    ]:
        total_def_stats += '<td>{}</td>'.format(sum(counts[True].values()))
        total_nondef_stats += '<td>{}</td>'.format(sum(counts[False].values()))
        total_stats += '<td><b>{}</b></td>'.format(sum(counts[False].values()) + sum(counts[True].values()))

    # Generate stats table
    table = stats_template.render(area_stats=area_stats,
                                  total_def_stats=total_def_stats,
                                  total_nondef_stats=total_nondef_stats,
                                  total_stats=total_stats)
    return table


def create_fail_table(name, device, op_status, oracle_vars, db_vars, where_match):
    """Generates an HTML table that highlights differences between Oracle and EPICS barcode/stdz params for a magnet.

    Args:
        name (str): The element name of the magnet.
        device (str): The device name of the magnet.
        op_status (str): The operation status of the magnet.
        oracle_vars (list[Any]): The barcode and standardize parameters from Oracle.
        db_vars (list[Any]): The barcode and standardize parameters from EPICS.
        where_match (list[bool]): Whether the Oracle and EPICS values of each paramater match.

    Returns:
        str: HTML code for a table that marks errors between the magnet's Oracle and EPICS barcode/stdz params in red.
    """
    cols_th = ['<th>{}</th>'.format(col[2]) for col in COLS[:-1]]
    oracle_row = ''
    epics_row = ''
    for i in range(len(COLS[:-1])):
        if i >= len(oracle_vars):
            oracle_row += '<td></td>'
            epics_row += '<td class="diff">{}</td>'.format(db_vars[i])
        elif i >= len(db_vars):
            oracle_row += '<td class="diff">{}</td>'.format(oracle_vars[i])
            epics_row += '<td></td>'
        elif not where_match[i]:
            oracle_row += '<td class="diff">{}</td>'.format(oracle_vars[i])
            epics_row += '<td class="diff">{}</td>'.format(db_vars[i])
        else:
            oracle_row += '<td>{}</td>'.format(oracle_vars[i])
            epics_row += '<td>{}</td>'.format(db_vars[i])

    cols = ''.join(cols_th)
    table = fail_template.render(name=name,
                                 device=device,
                                 op_status=op_status,
                                 cols=cols,
                                 oracle_row=oracle_row,
                                 epics_row=epics_row)
    return table


def create_fail_section(areas, fail_dict):
    """Creates an HTML section containing magnet barcode and standardize parameter mismatches.

    Args:
        areas (OrderedDict[str, Any]): The magnet areas represented as an ordered set.
        fail_dict (OrderedDict[str, list[tuple]]): A dict mapping areas to a list of failing magnets each as a tuple
            containing:

        - str: The element name.
        - str: The device name.
        - str: The operation status.
        - list[Any]: The barcode and standardize parameters from Oracle.
        - list[Any]: The barcode and standardize parameters from EPICS.

    Returns:
        str: HTML code containing tables highlighting magnet barcode/stdz parameter mismatches, separated by area.
    """
    fail_section = ''
    for area in areas:
        if fail_dict[area]:
            fail_section += '<hr>'
            fail_section += '<h3>{}</h3>'.format(area)
            for magnet in fail_dict[area]:
                fail_section += create_fail_table(*magnet)

    return fail_section


def create_missing_section(areas, missing_dict):
    """Creates an HTML section containing magnets missing barcode/standardize parameters from either Oracle or EPICS.

    Args:
        areas (OrderedDict[str, Any]): The magnet areas represented as an ordered set.
        missing_dict (OrderedDict[str, list[tuple]]): A dict mapping areas to a list of missing magnets each as a tuple
            containing:

        - str: The element name.
        - str: The device name.
        - str: The operation status.
        - list[Any]: The barcode and standardize parameters from Oracle.
        - list[Any]: The barcode and standardize parameters from EPICS.

    Returns:
        str: HTML code containing tables listing element names, device names, and operation statuses of magnets with
            barcode and standardize parameters missing from Oracle or EPICS, separated by area.
    """
    missing_section = ''
    for area in areas:
        if missing_dict[area]:
            magnet_rows = ''
            for name, device, op_status in missing_dict[area]:
                magnet_rows += '<tr><th>{}</th>'.format(name)
                magnet_rows += '<td>{}</td>'.format(device)
                magnet_rows += '<td>{}</td></tr>\n'.format(op_status)

            table = missing_template.render(area=area, magnet_rows=magnet_rows)
            missing_section += table

    return missing_section


def create_email(fail_count, pass_fail_table, fail_elem_table, missing_oracle_count, missing_oracle_elem_table,
                 missing_epics_count, missing_epics_elem_table):
    """Generates email content for the magnet barcode and standardize parameter report.

    Args:
        fail_count (int): The number of magnets with mismatched barcode and standardize parameters.
        pass_fail_table (str): HTML code for a table containing the number of passing and failing magnets for each area.
        fail_elem_table (str): HTML code containing tables showing magnet barcode/stdz mismatches, separated by area.
        missing_oracle_count (int): The number of magnets without barcode or standardize parameters from Oracle.
        missing_oracle_elem_table (str): HTML code containing tables listing magnets without barcode or standardize
            parameters from Oracle, separated by area.
        missing_epics_count (int): The number of magnets without barcode or standardize parameters from EPICS.
        missing_epics_elem_table (str): HTML code containing tables listing magnets without barcode or standardize
            parameters from EPICS, separated by area.

    Returns:
        str: HTML code, including the style specification, for the entire magnet barcode/standardize parameter report.
    """
    col_names = [col[2] for col in COLS]
    cols = ', '.join(col_names)
    timestamp = datetime.now().ctime()
    content = email_template.render(timestamp=timestamp,
                                    fail_count=fail_count,
                                    cols=cols,
                                    pass_fail_table=pass_fail_table,
                                    fail_elem_table=fail_elem_table,
                                    missing_oracle_count=missing_oracle_count,
                                    missing_epics_count=missing_epics_count,
                                    missing_oracle_elem_table=missing_oracle_elem_table,
                                    missing_epics_elem_table=missing_epics_elem_table)
    return content


def send_email(subject, message, sender, recipient):
    """Sends an email to the specified recipient(s).

    Args:
        subject (str): The subject line.
        message (str): The message as HTML code.
        sender (str): The email address of the sender.
        recipients (list[str]): The email address(es) of the recipient(s).
    """
    # Read config mgnt_email.cfg
    with open('mgnt_email.cfg', 'r') as f:
        email_config = json.load(f)

    msg = MIMEText(message, 'html')
    msg['Subject'] = '' + subject
    recipient_list = [recipient]
    msg['To'] = ','.join(recipient_list)
    msg['From'] = sender
    s = smtplib.SMTP(email_config['smtphost'])

    # Send email
    s.sendmail(sender, recipient_list, msg.as_string())
    s.quit()
    print('Email sent from {} to {}'.format(sender, ', '.join(recipient)))


def create_report(facility):
    """Performs barcode/stdz parameter comparison in the specified facility, generates a report, and sends it out.

    Args:
        facility (str): Specific facility from which to get magnet data, either `LCLS` or `FACET`.

    Raises:
        Exception: If `check_dev_pvs` returns an invalid status.

    Returns:
        tuple: A tuple containing:

        - str: HTML code containing tables highlighting magnet barcode/stdz parameter mismatches, separated by area.
        - bool: True if any magnets failed, False otherwise.
    """
    # Compare polynomial coefficients
    fail_elem_table = ''
    devices = get_all_magnets(facility)
    fields = [col[0] for col in COLS]
    stdz_info_dict = get_all_stdz_info(devices, fields)
    oracle_stdz_info = get_oracle_stdz_info(devices)
    areas = OrderedDict()
    fail_dict = defaultdict(list)
    missing_oracle_dict = defaultdict(list)
    missing_epics_dict = defaultdict(list)
    area_counts = defaultdict(Counter)
    pass_counts = defaultdict(Counter)
    fail_counts = defaultdict(Counter)
    missing_oracle_counts = defaultdict(Counter)
    missing_epics_counts = defaultdict(Counter)
    not_installed_counts = defaultdict(Counter)
    for device in devices:
        element, area, ca_name, op_status = [device[i] for i in [0, 2, 3, 6]]
        deferred = area.startswith('*')
        areas[area] = 1
        area_counts[deferred][area] += 1
        oracle_coeff, ca_coeff, where_matching, status = compare_dev_pvs(ca_name, COLS, stdz_info_dict,
                                                                         oracle_stdz_info)
        if status == Status.MATCHING:
            pass_counts[deferred][area] += 1
        elif status == Status.NOT_MATCHING:
            fail_dict[area].append((element, ca_name, op_status, oracle_coeff, ca_coeff, where_matching))
            fail_counts[deferred][area] += 1
        elif status == Status.NOT_IN_ORACLE:
            missing_oracle_dict[area].append((element, ca_name, op_status))
            missing_oracle_counts[deferred][area] += 1
        elif status == Status.NOT_IN_EPICS:
            missing_epics_dict[area].append((element, ca_name, op_status))
            missing_epics_counts[deferred][area] += 1
        else:
            raise Exception('Unknown status:', status)

        if not op_status or op_status.lower() == 'not installed':
            not_installed_counts[deferred][area] += 1

    fail_count = sum(fail_counts[False].values()) + sum(fail_counts[True].values())
    missing_oracle_count = sum(missing_oracle_counts[False].values()) + sum(missing_oracle_counts[True].values())
    missing_epics_count = sum(missing_epics_counts[False].values()) + sum(missing_epics_counts[True].values())

    # Create email
    pass_fail_table = create_stats_table(areas, area_counts, pass_counts, fail_counts, missing_oracle_counts,
                                         missing_epics_counts, not_installed_counts)
    fail_elem_table = create_fail_section(areas, fail_dict)
    missing_oracle_elem_table = create_missing_section(areas, missing_oracle_dict)
    missing_epics_elem_table = create_missing_section(areas, missing_epics_dict)
    content = create_email(fail_count, pass_fail_table, fail_elem_table, missing_oracle_count,
                           missing_oracle_elem_table, missing_epics_count, missing_epics_elem_table)
    failed = fail_count > 0

    return content, failed


def get_user_email():
    """Gets the email address of the user running this script."""
    user_details = pwd.getpwuid(os.getuid())
    return user_details.pw_name + "@slac.stanford.edu"


if __name__ == '__main__':
    # Recommend mcclogin if user is on lcls-dev2 or lcls-dev3
    hostname = socket.gethostname()
    if hostname in ('lcls-dev2', 'lcls-dev3'):
        print('WARNING: Please run this script on mcclogin instead of {} so that '
              'production PVs are readable.\n'.format(hostname))

    # Parse arguments
    user_email = get_user_email()
    parser = argparse.ArgumentParser(
        description='Run magnet parameter comparison report. By default, the report is sent '
        "to the user's email ({}).".format(user_email))
    parser.add_argument('-f', '--facility', default='LCLS', help='compare magnet parameters for a specific facility')
    parser.add_argument('-e', '--email', dest='recipient', help='send the report to a different email')
    parser.add_argument('-n',
                        '--no-email',
                        action='store_true',
                        help='run parameter comparison but do not send email (for testing only)')

    args = parser.parse_args()

    # Go to script directory
    script_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    os.chdir(script_path)

    # Initialize Jinja templates
    environment = Environment(loader=FileSystemLoader('templates'))
    fail_template = environment.get_template('mgnt_fail_table.template')
    missing_template = environment.get_template('mgnt_missing_table.template')
    stats_template = environment.get_template('mgnt_stats.template')
    email_template = environment.get_template('mgnt_stdz_email.template')

    # Compare magnet parameters
    content, failed = create_report(args.facility)

    # Send email
    if not args.no_email:
        if args.recipient:
            recipient = args.recipient
        else:
            recipient = user_email

        subject = 'Magnet Parameter Comparison Report - {}'.format('FAILED' if failed else 'PASSED')
        send_email(subject, content, user_email, recipient)

    # Print status
    print('All done')
