# Copyright (c) Facebook, Inc. and its affiliates.
from collections.abc import Mapping
from detectron2.utils.logger import setup_logger
import pandas as pd
from detectron2.utils import comm

def print_csv_format(cfg, results):
    """
    Print main metrics in a format similar to Detectron,
    so that they are easy to copypaste into a spreadsheet.

    Args:
        results (OrderedDict[dict]): task_name -> {metric -> score}
            unordered dict can also be printed, but in arbitrary order
    """
    assert isinstance(results, Mapping) or not len(results), results
    logger = setup_logger(cfg.OUTPUT_DIR, name = __name__, distributed_rank = comm.get_rank())
    for task, res in results.items():
        if isinstance(res, Mapping):
            # Don't print "AP-category" metrics since they are usually not tracked.
            # important_res = [(k, v) for k, v in res.items() if "-" not in k]
            important_res = [(k, v) for k, v in res.items()]
            df = pd.DataFrame(important_res, columns=["Metric", "Value"])
            df["Task"] = task
            df = df[["Task"] + list(df.columns[:-1])]
            logger.info("\n"+df.to_markdown(index=False))
            per_class_res = ["{}:{} ".format(k.split("-")[1],round(v,4)) for k, v in res.items() if "-" in k]
            logger.info("".join(per_class_res))
        else:
            logger.info(f"copypaste: {task}={res}")
