from typing import List
from typing import Dict
import copy


def process_record_merge_summary(record_list: List[Dict]) -> List[Dict]:
    """
    merge records that have same step summary into single one record

    :param record_list: list of record
    :return: list of record
    """
    record_dict = {}  # step -> record
    for record in record_list:
        step = record["step"]

        if step not in record_dict:
            record_dict[step] = record
        else:
            new_record = copy.deepcopy(
                record
            )  # new record have newer wall_time, record_list are ordered

            old_record = record_dict[step]

            old_key = set(old_record["summary"].keys())
            current_key = set(record["summary"].keys())
            if old_key & current_key:
                raise ValueError("{}, {} have same keys".format(old_record, record))

            old_summary = old_record["summary"]
            new_summary = record["summary"]
            new_summary.update(old_summary)

            new_record["summary"] = new_summary

            record_dict[step] = new_record

    return list(sorted(record_dict.values(), key=lambda x: x["step"]))