from typing import List
from typing import Dict
from datetime import datetime


def filter_opt_tasks_by_time(tasks: List[Dict], logger) -> Dict:
    """
    Filter a set of tasks to select the latest completed one.

    Args:
        tasks: the set of tasks to filer
        logger:

    Returns:
        selected latest task
    """
    if len(tasks) == 0:
        raise RuntimeError("Cannot select latest from 0 tasks")
    elif len(tasks) == 1:
        return tasks[0]
    else:
        completed = [(datetime.fromisoformat(t["completed_at"]), t) for t in tasks]
        sorted_by_completed = sorted(completed, key=lambda pair: pair[0])
        latest_pair = sorted_by_completed[-1]
        selected = latest_pair[1]

        task_ids = [t["task_id"] for t in tasks]
        logger.warning(
            f"Select the latest optimization task {selected['task_id']} completed at "
            f"{selected['completed_at']} from a set of tasks: {task_ids}."
        )

        return selected