#!/usr/bin/env python


import argparse
import sys


import timing


ignore = ["TimeStep"]


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("jobs", nargs="+")
    p.add_argument("--normalize", action="store_true")
    p.add_argument("--extra-columns", nargs="*")
    args = p.parse_args()

    columns = [
        "BC:cells",
        "BC:dynamicecm",
        "Sweep:Cells",
        "Sweep:DynamicECM",
        "Sweep:DynamicECMDampers",
    ] + (args.extra_columns or [])

    dfs = dict()
    labels = []
    for label, jobid in [jobarg.split(":") for jobarg in args.jobs]:
        jobs, excluded_array_indices = timing.get_jobs(jobid)
        df = timing.load_array_mean_timings(jobid, excluded_array_indices).mean()
        dfs[label] = df
        labels.extend(df.index)

    labels = set(labels)
    print(",".join(["label"] + columns + ["Other"]))

    values_by_label = dict()
    for label, df in dfs.items():
        values = {"Other": 0}
        for c in df.index:
            if c in ignore:
                continue
            elif c not in columns:
                values["Other"] += df[c]
                print(f"Others+= {c}={df[c]}", file=sys.stderr)
            else:
                values[c] = df[c]
        values_by_label[label] = values

    if args.normalize:
        print("Normalizing data to 100%...", file=sys.stderr)
        for values in values_by_label.values():
            row_length = sum(values.values())
            for c in values.keys():
                values[c] *= 100 / row_length

    for label, values in values_by_label.items():
        print(label + "," + ",".join(f"{values[c]}" for c in columns + ["Other"]))
