"""Type-7 quantiles for invented durations. Python 3.10+, standard library only."""
import argparse
import json
from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_UP
from pathlib import Path

D = Decimal


def display(value):
    return str(value.quantize(D("0.01"), rounding=ROUND_HALF_UP))


def percentile(sorted_values, p):
    if not sorted_values or not D(0) <= p <= D(1):
        raise ValueError("Require nonempty observations and a probability in [0, 1]")
    h = D(len(sorted_values) - 1) * p
    j = int(h.to_integral_value(rounding=ROUND_FLOOR))
    g = h - j
    low, high = D(sorted_values[j]), D(sorted_values[min(j + 1, len(sorted_values) - 1)])
    return low + g * (high - low)


def summarize(values):
    if not values or any(type(value) is not int or value < 0 for value in values):
        raise ValueError("This exercise requires nonempty, nonnegative integer durations")
    ordered = sorted(values)
    return {"n": len(ordered), "sorted_ms": ordered, "mean_ms": display(D(sum(ordered)) / len(ordered)),
            "p50_ms": display(percentile(ordered, D("0.50"))),
            "p90_ms": display(percentile(ordered, D("0.90"))),
            "p95_ms": display(percentile(ordered, D("0.95"))), "max_ms": ordered[-1]}


def calculate(data):
    windows, all_values, p95_values = [], [], []
    for window in data["windows"]:
        values = window["durations_ms"]
        summary = summarize(values)
        windows.append({"name": window["name"], **summary})
        all_values.extend(values)
        p95_values.append((len(values), percentile(sorted(values), D("0.95"))))
    if not windows:
        raise ValueError("At least one window is required")
    unweighted = sum(value for _, value in p95_values) / len(p95_values)
    weighted = sum(D(count) * value for count, value in p95_values) / len(all_values)
    return {"convention": "Type 7", "unit": "milliseconds", "windows": windows,
            "pooled": summarize(all_values), "unweighted_mean_of_window_p95_ms": display(unweighted),
            "count_weighted_mean_of_window_p95_ms": display(weighted)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--check", type=Path)
    args = parser.parse_args()
    result = calculate(json.loads(args.input.read_text(encoding="utf-8")))
    print(json.dumps(result, indent=2))
    if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
        parser.exit(1, "Answer mismatch: compare the printed values with your answer.\n")


if __name__ == "__main__":
    main()
