"""Compare exact nearest-rank p95 with merged cumulative bucket counts."""
import json
import platform
import sys
from bisect import bisect_left
from fractions import Fraction
from itertools import accumulate

BOUNDS = (25, 50, 100, 250, 500, 1000)


def p95_rank(total):
    if total == 0:
        raise ValueError("no observations")
    return (95 * total + 99) // 100


def p95(samples):
    return sorted(samples)[p95_rank(len(samples)) - 1]


def cumulative(samples, bounds=BOUNDS):
    if tuple(sorted(set(bounds))) != bounds:
        raise ValueError("expected strictly increasing boundaries")
    bins = [0] * (len(bounds) + 1)
    for value in samples:
        bins[bisect_left(bounds, value)] += 1
    return dict(zip((*bounds, "+Inf"), accumulate(bins)))


def merge(*histograms):
    if any(tuple(hist) != tuple(histograms[0]) for hist in histograms[1:]):
        raise ValueError("different bucket boundaries")
    return {bound: sum(hist[bound] for hist in histograms) for bound in histograms[0]}


def location(hist):
    rank = p95_rank(hist["+Inf"])
    lower = None
    for upper, count in hist.items():
        if count >= rank:
            return [lower, None if upper == "+Inf" else upper]
        lower = upper


def scenario(node_a, node_b):
    combined = node_a + node_b
    hist_a, hist_b = cumulative(node_a), cumulative(node_b)
    merged = merge(hist_a, hist_b)
    assert merged == cumulative(combined)
    node_quantiles = [p95(node_a), p95(node_b)]
    combined_quantile = p95(combined)
    assert min(node_quantiles) <= combined_quantile <= max(node_quantiles)
    return {
        "node_counts": [len(node_a), len(node_b)],
        "node_p95_ms": node_quantiles,
        "merged_rank": p95_rank(len(combined)),
        "merged_p95_ms": combined_quantile,
        "node_cumulative_counts": [hist_a, hist_b],
        "merged_cumulative_counts": merged,
        "p95_bucket_ms": location(merged),
        "within_80_ms": sum(value <= 80 for value in combined),
        "within_100_ms": merged[100],
    }


def run():
    fast = [40] * 949
    node_b = [20] * 94 + [900] * 6
    baseline = scenario(fast + [100] * 51, node_b)
    longer_tail = scenario(fast + [100] + [300] * 50, node_b)
    same_bucket = scenario(fast + [60] * 51, node_b)
    exactly_95 = scenario(fast + [100] * 2 + [300] * 49, node_b)
    assert baseline["node_counts"] == longer_tail["node_counts"] == [1000, 100]
    assert baseline["node_p95_ms"] == longer_tail["node_p95_ms"] == [100, 900]
    assert baseline["merged_rank"] == 1045
    assert [case["merged_p95_ms"] for case in (baseline, longer_tail, same_bucket, exactly_95)] == [100, 300, 60, 100]
    assert baseline["merged_cumulative_counts"] == same_bucket["merged_cumulative_counts"]
    assert baseline["within_80_ms"] == 1043 < 1045 <= same_bucket["within_80_ms"] == 1094
    assert [case["within_100_ms"] for case in (baseline, longer_tail, exactly_95)] == [1094, 1044, 1045]
    assert baseline["p95_bucket_ms"] == same_bucket["p95_bucket_ms"] == [50, 100]
    assert longer_tail["p95_bucket_ms"] == [250, 500]
    assert cumulative([100])[100] == 1
    assert location(cumulative([1500])) == [1000, None]
    assert p95([11, 15, 18, 210]) == 210
    for operation in (
        lambda: location(cumulative([])),
        lambda: merge(cumulative([50]), cumulative([50], (50, 200))),
    ):
        try:
            operation()
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")

    counts = baseline["merged_cumulative_counts"]
    # The rank here is an integer. Illustrate interpolation inside (50, 100].
    interpolation = 50 + 50 * Fraction(1045 - counts[50], counts[100] - counts[50])
    weighted = Fraction(1000 * 100 + 100 * 900, 1100)
    return {
        "environment": {
            "os": platform.system(),
            "os_version": platform.mac_ver()[0] or platform.release(),
            "machine": platform.machine(),
            "python": sys.version.split()[0],
        },
        "bucket_upper_bounds_ms": [*BOUNDS, "+Inf"],
        "node_p95_simple_mean_ms": 500,
        "node_p95_weighted_mean_ms": round(float(weighted), 6),
        "baseline": baseline,
        "longer_tail": longer_tail,
        "same_bucket": same_bucket,
        "exactly_95_percent": exactly_95,
        "baseline_and_same_bucket_linear_estimate_ms": round(float(interpolation), 6),
        "overflow_only_p95_bucket_ms": location(cumulative([1500])),
        "four_observations_p95_ms": p95([11, 15, 18, 210]),
        "rejected": ["empty observations", "mismatched bucket boundaries"],
    }


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
