# Copyright 2023 Efabless Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from typing import Mapping, Tuple, Dict, Any, Callable, Iterable

modifier_rx = re.compile(r"([\w\-]+)\:([\w\-]+)")


def parse_metric_modifiers(metric_name: str) -> Tuple[str, Mapping[str, str]]:
    """
    Parses a metric name into a base and modifiers as specified in
    the `Metrics4ML standard <https://github.com/ieee-ceda-datc/datc-rdf-Metrics4ML>`_.

    :param metric_name: The name of the metric as generated by a utility.
    :returns: A tuple of the base part as a string, then the modifiers as
        a key-value mapping.
    """
    mn_mut = metric_name.split("__")
    modifiers = {}
    i = len(mn_mut) - 1
    if ":" in mn_mut[i]:
        modifier_list = mn_mut[i].split(":")
        if len(modifier_list) % 2 == 0:
            for i in range(0, len(modifier_list) - 1, 2):
                modifiers[modifier_list[i]] = modifier_list[i + 1]
            mn_mut.pop()
    return "__".join(mn_mut), modifiers


def aggregate_metrics(
    input: Dict[str, Any],
    aggregator_by_metric: Dict[str, Tuple[Any, Callable[[Iterable], Any]]],
) -> Dict[str, Any]:
    aggregated: Dict[str, Any] = {}
    for name, value in input.items():
        metric_name, modifiers = parse_metric_modifiers(name)
        if len(modifiers) != 1:
            # No modifiers = final aggregate, don't double-represent in sums
            # >1 modifiers = n-level nesting, not supported atm
            continue
        entry = aggregator_by_metric.get(metric_name)
        if entry is None:
            continue
        start, aggregator = entry
        current = aggregated.get(metric_name) or start
        aggregated[metric_name] = aggregator([current, value])

    final_values = input.copy()
    final_values.update(aggregated)
    return final_values
