import math


def add_aggregate_info(site_and_date_info, percentage, sorted_names):
    """
    Function is used to add an 'aggregate metric' that
    summarizes all of the data quality issues for a
    particular site on a particular date.

    NOTE: This function DOES NOT take the weighted value
        of all of these metrics. This is merely to attach
        the aggregate statistic.

    NOTE: This is for the DICTIONARY with the date as the
    first set of keys.

    :param
    site_and_date_info (dict): dictionary with key:value
        of date:additional dictionaries that contain metrics
        for each HPO's data quality by type

    percentage (boolean): used to determine whether or not the
        number is a simple record count (e.g. duplicates)
        versus the percentage of records (e.g. the success rate
        for each of the tables)

    sorted_names (lst): list of the names that should have an
        aggregate statistic analyzed (e.g. avoiding 'avarage'
        statistics)

    :return:
    site_and_date_info (dict): same as input parameter but
        now each site and date has an added aggregate
        statistic.
    """
    for date in site_and_date_info.keys():
        date_report = site_and_date_info[date]
        date_metric, num_iterated = 0, 0

        for site in sorted_names:
            table_metrics = date_report[site]
            date_metric, num_iterated = 0, 0

            for table in table_metrics.keys():
                stat = table_metrics[table]
                if not math.isnan(stat):
                    date_metric += stat
                    num_iterated += 1

        # NOTE: 'AGGREGATE INFO' SHOULD NOT BE USED FOR
        # THE PERCENTAGE METRIC. THIS IS BECAUSE THE
        # FIRST 'AGGREGATE INFO' DOES NOT WEIGHT SITES
        # BY THEIR RELATIVE CONTRIBUTIONS (BY # OF ROWS).
        if percentage and num_iterated > 0:
            date_metric = date_metric / num_iterated
        elif percentage and num_iterated == 0:
            date_metric = float('NaN')

        date_report['aggregate_info'] = date_metric

    return site_and_date_info