from typing import Dict
from typing import List


def create_related_cve_list_for_machine(machines):
    """
    Parses the machines list to include a CVE list for each machine by ID.
    For example,
    machines = [{'ID': 1, 'CVE': 'CVE-1'},{'ID': 1, 'CVE': 'CVE-2'},{'ID': 2, 'CVE': 'CVE-1'}]

    the output after the for loop will be:
    machines = [{'ID': 1, ['CVE': 'CVE-1','CVE-2']},{'ID': 1, ['CVE': 'CVE-1','CVE-2']},{'ID': 2, 'CVE': ['CVE-1']}]

    and the output after remove duplicates will be:
    unique_machines = [{'ID': 1, 'CVE': ['CVE-1','CVE-2']},{'ID': 2, 'CVE': ['CVE-1']}]
    """
    machine_id_to_cve_list: Dict[str, List[str]] = {}
    for machine in machines:
        machine_id = machine.get('ID')
        cve_id = machine.get('CVE')
        if not machine_id_to_cve_list.get(machine_id):
            machine_id_to_cve_list[machine_id] = [cve_id]
        else:
            machine_id_to_cve_list[machine_id].append(cve_id)
        machine.pop('CVE')
        machine['CVE'] = machine_id_to_cve_list[machine_id]

    # handle duplicates
    unique_machines = []
    for machine in machines:
        if machine not in unique_machines:
            unique_machines.append(machine)
    return unique_machines