#!/usr/bin/env python
# ==============================================================
#
#  Abs:   Script for comparing magnet polynomial coefficients
#         in EPICS and in Oracle
#
#  Name:  mgnt_poly_compare.py
#
#  Usage: mgnt_poly_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)
#         Go to script directory before accessing templates
#         Print done message
#     15-Dec-2022, A. Le (anle)
#         Change index where polynomial coefficients start
#     14-Dec-2022, A. Le (anle)
#         Add ability to trim different kinds of blanks
#     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
#     17-Jun-2022, A. Le (anle)
#         Fix Oracle polynomial retrieval
#         Add switch for recipient of failing reports
#     31-May-2022, A. Le (anle)
#         Make code compatible with Python 2 and 3
#     19-Nov-2021, A. Le (anle)
#         Add facility argument
#     01-Oct-2021, A. Le (anle)
#         Prevent floating-point rounding error
#     26-Aug-2021, A. Le (anle)
#         Avoid writing report to file for now
#         Add abbreviated options
#     23-Aug-2021, A. Le (anle)
#         Rename to mgnt_poly_compare.py
#         Send report to user by default
#         Warn user if script is called from lcls-dev2 or lcls-dev3
#     20-Aug-2021, A. Le (anle)
#         Make script directory independent
#     12-Aug-2021, A. Le (anle)
#         Clarify which Oracle database is examined
#     14-Jul-2021, A. Le (anle)
#         Ignore extra columns from Oracle output
#     31-Aug-2020, A. Le (anle)
#         Clean up code
#     17-Aug-2020, A. Le (anle)
#         Call caget once
#     13-Aug-2020, A. Le (anle)
#         Adjust formatting
#         Use pyepics for caget
#         Add switch to send to different email
#     17-Jul-2020, A. Le (anle)
#         Rename variables
#         Add "not installed" column
#         -Add space between fail and missing sections
#         -Add message before stats table
#     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

import epics
import numpy as np
from jinja2 import Environment, FileSystemLoader

from mgnt_get_elements import get_all_magnets
from mgnt_get_poly import round_dec_places, trim_blanks


class Status(Enum):
    """Enumerates status codes for polynomial comparison."""

    NOT_IN_EPICS = 1
    """The EPICS polynomial is missing."""

    NOT_IN_ORACLE = 2
    """The Oracle polynomial is missing."""

    NOT_MATCHING = 3
    """The EPICS and Oracle polynomials do not match."""

    MATCHING = 4
    """The EPICS and Oracle polynomials match."""


def get_all_poly(devices):
    """Gets all polynomial coefficients from EPICS.

    Args:
        devices (list[tuple]): The magnets as tuples.

    Returns:
        dict[str, numpy.ndarray]: A mapping between device names and polynomial coefficients from EPICS.
    """
    # Gets all polynomial coefficients from EPICS
    poly_dict = {}
    pvs = [device[3] + ':IVB' for device in devices]
    polys = epics.caget_many(pvs, timeout=2)
    for device, poly in zip(devices, polys):
        poly_dict[device[3]] = poly

    return poly_dict


def process_epics_poly(ca_name, poly_dict):
    """Rounds all the EPICS coefficients for one magnet to 6 decimal places.

    Args:
        ca_name (str): The device name of the magnet.
        poly_dict (dict[str, numpy.ndarray]): The dict containing device names and their corresponding polynomials.

    Returns:
        tuple: A tuple containing:

        - list(float): The rounded coefficients.
        - bool | Status: True if a polynomial was found for the given device name, Status.NOT_IN_EPICS otherwise.
    """
    coeffs = poly_dict[ca_name]
    if coeffs is not None:
        rounded_coeffs = [round_dec_places(coeff, 6) for coeff in coeffs]
        return rounded_coeffs, True

    return [], Status.NOT_IN_EPICS


def process_oracle_poly(oracle_poly):
    """Rounds all the Oracle coefficients for one magnet to 6 decimal places.

    Args:
        oracle_poly (tuple[float | None, ...]): The polynomial coefficients from Oracle.

    Returns:
        tuple: A tuple containing:

        - list(float): The rounded coefficients.
        - bool: Whether the provided polynomial was valid.
    """
    try:
        trimmed_coeffs = trim_blanks(oracle_poly)
        if not trimmed_coeffs:
            return [], Status.NOT_IN_ORACLE

        rounded_coeffs = [round_dec_places(float(coeff), 6) for coeff in trimmed_coeffs]
        return rounded_coeffs, True
    except ValueError:
        return [], Status.NOT_IN_ORACLE


def check_dev_poly(device, poly_dict, oracle_poly):
    """Ensures that the EPICS and Oracle polynomials match for a magnet.

    Args:
        device (str): The device name of the magnet.
        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[float]: The rounded coefficients from Oracle.
        - list[float]: The rounded coefficients from EPICS.
        - Status: Whether the polynomials match or one of them is missing.
    """
    ca_coeff, ca_status = process_epics_poly(device, poly_dict)
    oracle_coeff, oracle_status = process_oracle_poly(oracle_poly)
    if oracle_status == Status.NOT_IN_ORACLE:
        status = oracle_status
    elif ca_status == Status.NOT_IN_EPICS:
        status = ca_status
    else:
        if np.array_equal(ca_coeff, oracle_coeff):
            status = Status.MATCHING
        else:
            status = Status.NOT_MATCHING

    return oracle_coeff, ca_coeff, status


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 magnet polynomial 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 correct polynomials 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 incorrect polynomials 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 polynomials 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 polynomials 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_stats = ''
    total_def_stats = ''
    total_nondef_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_coeff, db_coeff):
    """Generates an HTML table that highlights the differences between Oracle and EPICS polynomials 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_coeff (list[float]): The polynomial coefficients from Oracle.
        db_coeff (list[float]): The polynomial coefficients from EPICS.

    Returns:
        str: HTML code for a table that marks inconsistencies between the magnet's Oracle and EPICS polynomials in red.
    """
    num_vars = max(len(oracle_coeff), len(db_coeff))
    poly_vars_th = ['<th>{}</th>'.format(chr(i + 65)) for i in range(num_vars)]
    oracle_row = ''
    epics_row = ''
    for i in range(num_vars):
        if i >= len(oracle_coeff):
            oracle_row += '<td></td>'
            epics_row += '<td class="diff">{}</td>'.format(db_coeff[i])
        elif i >= len(db_coeff):
            oracle_row += '<td class="diff">{}</td>'.format(oracle_coeff[i])
            epics_row += '<td></td>'
        elif oracle_coeff[i] != db_coeff[i]:
            oracle_row += '<td class="diff">{}</td>'.format(oracle_coeff[i])
            epics_row += '<td class="diff">{}</td>'.format(db_coeff[i])
        else:
            oracle_row += '<td>{}</td>'.format(oracle_coeff[i])
            epics_row += '<td>{}</td>'.format(db_coeff[i])

    cols = ''.join(poly_vars_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 polynomial 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[float]: The polynomial coefficients from Oracle.
        - list[float]: The polynomial coefficients from EPICS.

    Returns:
        str: HTML code containing tables highlighting magnet polynomial 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 polynomials 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[float]: The polynomial coefficients from Oracle.
        - list[float]: The polynomial coefficients from EPICS.

    Returns:
        str: HTML code containing tables listing element names, device names, and operation statuses of magnets with
            polynomials 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 polynomial report.

    Args:
        fail_count (int): The number of magnets with mismatched polynomials.
        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 highlighting magnet polynomial mismatches, separated by area.
        missing_oracle_count (int): The number of magnets without Oracle polynomials.
        missing_oracle_elem_table (str): HTML code containing tables listing magnets without Oracle polynomials,
            separated by area.
        missing_epics_count (int): The number of magnets without EPICS polynomials.
        missing_epics_elem_table (str): HTML code containing tables listing magnets without EPICS polynomials,
            separated by area.

    Returns:
        str: HTML code, including the style specification, for the entire magnet polynomial report.
    """
    timestamp = datetime.now().ctime()
    content = email_template.render(timestamp=timestamp,
                                    fail_count=fail_count,
                                    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, recipients):
    """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
    msg['To'] = ','.join(recipients)
    msg['From'] = sender
    s = smtplib.SMTP(email_config['smtphost'])

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


def create_report(facility):
    """Performs magnet polynomial 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_poly` returns an invalid status.

    Returns:
        tuple: A tuple containing:

        - str: HTML code containing tables highlighting magnet polynomial mismatches, separated by area.
        - bool: True if any magnets failed, False otherwise.
    """
    # Compare polynomial coefficients
    fail_elem_table = ''
    devices = get_all_magnets(facility)
    poly_dict = get_all_poly(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]]
        oracle_poly = device[31:]
        deferred = area.startswith('*')
        areas[area] = 1
        area_counts[deferred][area] += 1
        oracle_coeff, ca_coeff, status = check_dev_poly(ca_name, poly_dict, oracle_poly)
        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))
            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 polynomial 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 polynomials for a specific facility')
    parser.add_argument('-e', '--email', dest='recipient', help='send the report to a different email')
    parser.add_argument('-ef', '--email-failed', dest='fail_recipient', help='send failing reports to an email')
    parser.add_argument('-n',
                        '--no-email',
                        action='store_true',
                        help='run polynomial 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_poly_email.template')

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

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

        if args.fail_recipient and failed:
            recipients.append(args.fail_recipient)

        subject = 'Magnet Polynomial Comparison Report - {}'.format('FAILED' if failed else 'PASSED')
        recipients = [r for r in recipients if 'magnets' not in r]
        send_email(subject, content, user_email, recipients)

    # Print status
    print('All done')
