#!/usr/bin/env python3
"""Compute process-paired effects from verified lookup benchmark windows."""

import argparse
import json
from math import comb
from pathlib import Path
from statistics import median


def median_interval(values):
    """Exact, at least 95% sign interval for a continuous population median."""
    ordered = sorted(values)
    n = len(ordered)
    best = None
    tail = 0
    for index in range(n // 2):
        tail += comb(n, index)
        coverage = 1 - 2 * tail / 2**n
        if coverage < 0.95:
            break
        best = {"lower": ordered[index], "upper": ordered[-index - 1], "coverage": coverage}
    return best


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("report", type=Path, help="benchmark-lookup JSON report")
    parser.add_argument("verified_windows", type=Path, help="summarize-warm-windows JSON output")
    parser.add_argument("--reference", required=True, help="profile whose per-process time is the denominator")
    args = parser.parse_args()
    report = json.loads(args.report.read_text())
    summary = json.loads(args.verified_windows.read_text())
    groups = summary["process_medians"]
    if args.reference not in groups:
        parser.error(f"unknown reference {args.reference}")
    reference = {r["trial"]: r for r in groups[args.reference]}
    comparisons = {}
    for profile, rows in groups.items():
        if profile == args.reference:
            continue
        values = {r["trial"]: r for r in rows}
        if values.keys() != reference.keys() or len(values) != len(rows):
            parser.error(f"{profile} does not have the same unique process blocks as the reference")
        comparisons[profile] = {}
        for metric in ("thread_cpu_ms", "wall_ms", "process_wall_s"):
            ratios = [values[trial][metric] / reference[trial][metric] for trial in sorted(reference)]
            comparisons[profile][metric] = {
                "trial_ratios": ratios,
                "ratio_median": median(ratios),
                "exact_median_interval": median_interval(ratios),
            }
    phases = {}
    for profile in groups:
        trials = [r for r in report["trials"] if r["profile"] == profile]
        if {r["trial"] for r in trials} != set(reference) or len(trials) != len(reference):
            parser.error(f"{profile} has mismatched raw trial records")
        phase_fields = {"setup_ns": "setup_s", "warmup_ns": "warmup_s"}
        phases[profile] = {
            name: median(r[key] for r in trials) / 1e9
            for key, name in phase_fields.items() if all(key in r for r in trials)
        }
        if all("logged_guest_compilation_ms" in r for r in trials):
            phases[profile]["logged_guest_compilation_s"] = (
                median(r["logged_guest_compilation_ms"] for r in trials) / 1000
            )
    print(json.dumps({
        "reference": args.reference,
        "fresh_process_blocks": sorted(reference),
        "ratios_are_candidate_over_reference": True,
        "paired_comparisons": comparisons,
        "phase_medians_seconds": phases,
        "interval_assumption": "Independent paired blocks on the measured host, no ties for exact coverage.",
    }, indent=2))


if __name__ == "__main__":
    main()
