"""sonusai summarize_metric_spenh

usage: summarize_metric_spenh [-hr] [-s SORT] LOC

options:
    -h, --help
    -s SORT, --sort SORT            Sort by SORT column. [default: MIXID]
    -r, --reverse                   Reverse sort order.

Summarize speech enhancement metrics results using data generated by SonusAI calc_metric_spenh.

Inputs:
    LOC         A SonusAI calc_metric_spenh results directory.

"""


def summarize_metric_spenh(location: str, by: str = "MIXID", reverse: bool = False) -> str:
    import glob

    import pandas as pd

    files = sorted(glob.glob(location + "/*_metric_spenh.txt"))
    need_header = True
    header = ["MIXID"]
    data = []
    for file in files:
        with open(file) as f:
            for i, line in enumerate(f):
                if i == 1 and need_header:
                    need_header = False
                    header.extend(line.strip().split())
                elif i == 2:
                    data.append(line.strip().split())
                    break

    df = pd.DataFrame(data, columns=header)  # pyright: ignore [reportArgumentType]
    df[header[0:-2]] = df[header[0:-2]].apply(pd.to_numeric, errors="coerce")
    return df.sort_values(by=by, ascending=not reverse).to_string(index=False)


def main():
    from docopt import docopt

    from sonusai import __version__ as sai_version
    from sonusai.utils import trim_docstring

    args = docopt(trim_docstring(__doc__), version=sai_version, options_first=True)

    by = args["--sort"]
    reverse = args["--reverse"]
    location = args["LOC"]

    print(summarize_metric_spenh(location, by, reverse))


if __name__ == "__main__":
    from sonusai import exception_handler
    from sonusai.utils import register_keyboard_interrupt

    register_keyboard_interrupt()
    try:
        main()
    except Exception as e:
        exception_handler(e)
