"""Compare matched HPCG reports and print median timings and observed ranges."""

import argparse
import csv
import math
import statistics
import sys
from pathlib import Path

TIMINGS = {
    "SpMV time (s)": "Benchmark Time Summary::SpMV",
    "Multigrid time (s)": "Benchmark Time Summary::MG",
    "Total time (s)": "Benchmark Time Summary::Total",
    "Raw SpMV (GFLOP/s)": "GFLOP/s Summary::Raw SpMV",
    "Final rating (GFLOP/s)": "Final Summary::HPCG result is VALID with a GFLOP/s rating of",
}
WORKLOAD = (
    "Global Problem Dimensions::Global nx",
    "Global Problem Dimensions::Global ny",
    "Global Problem Dimensions::Global nz",
    "Machine Summary::Distributed Processes",
    "Machine Summary::Threads per processes",
    "Linear System Information::Number of Nonzero Terms",
    "Floating Point Operations Summary::Raw SpMV",
)


def read_report(path):
    fields = dict(
        line.rsplit("=", 1)
        for line in path.read_text(encoding="utf-8-sig").splitlines()
        if "=" in line
    )
    try:
        workload = tuple(fields[key] for key in WORKLOAD)
        values = [float(fields[key]) for key in TIMINGS.values()]
    except (KeyError, ValueError) as error:
        raise ValueError(f"{path}: expected a complete VALID HPCG report ({error})") from error
    if any(not math.isfinite(value) or value <= 0 for value in values):
        raise ValueError(f"{path}: timings and rates must be finite and positive")
    return workload, values


def summarize(baseline, candidate):
    if len(baseline) != len(candidate) or not baseline:
        raise ValueError("Supply the same nonzero number of reports for both variants.")
    paths = [path.resolve() for path in (*baseline, *candidate)]
    if len(set(paths)) != len(paths):
        raise ValueError("Each report must be a distinct file.")
    reports = [read_report(path) for path in paths]
    workload = reports[0][0]
    if any(signature != workload for signature, _ in reports):
        raise ValueError("Reports differ in grid, rank/thread counts, nonzeros or SpMV work.")
    split = len(baseline)
    for i, label in enumerate(TIMINGS):
        left = [values[i] for _, values in reports[:split]]
        right = [values[i] for _, values in reports[split:]]
        a, b = statistics.median(left), statistics.median(right)
        yield label, a, b, (b / a - 1) * 100, min(left), max(left), min(right), max(right)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--baseline", nargs="+", required=True, type=Path)
    parser.add_argument("--candidate", nargs="+", required=True, type=Path)
    args = parser.parse_args()
    try:
        rows = list(summarize(args.baseline, args.candidate))
    except (OSError, ValueError) as error:
        parser.error(str(error))
    writer = csv.writer(sys.stdout, lineterminator="\n")
    writer.writerow(("metric", "baseline_median", "candidate_median", "change_pct",
                     "baseline_min", "baseline_max", "candidate_min", "candidate_max"))
    for label, *values in rows:
        writer.writerow([label, *(format(value, ".8g") for value in values)])


if __name__ == "__main__":
    main()
