from typing import List
import json


def compute_averages(perf_metric: str, perf_by_tag: List[dict]) -> dict:
    """
    Computes the average metrics from the per direction metrics.

    The output format match the one from vanilla `eval` method,
    and is ready to be put into the sql database.
    """
    avg_metrics = {}
    metric_names = {key for perf in perf_by_tag for key in perf["perf_dict"]}
    for key in metric_names:
        scores = [perf["perf_dict"][key] for perf in perf_by_tag]
        avg_metrics[key] = sum(scores) / len(scores)

    perf = avg_metrics[perf_metric]
    score_obj = {
        "perf": perf,
        "pretty_perf": f"{perf:.2f}",  # this is a BLEU score
        "metadata_json": json.dumps({**avg_metrics, "perf_by_tag": perf_by_tag}),
    }
    return score_obj