"""Exact arithmetic and synthetic counterexamples, not fleet-trace replication."""
import argparse
from fractions import Fraction
from hashlib import sha256
import json
from math import ceil
from pathlib import Path

REVIEW_DATE = "2026-10-15"
SOURCE = "https://www.usenix.org/system/files/conference/fast16/fast16-papers-hao.pdf"


def union_model(p, n):
    if not isinstance(p, Fraction) or not 0 <= p <= 1:
        raise ValueError("p must be a Fraction between zero and one")
    if type(n) is not int or n < 1:
        raise ValueError("n must be a positive integer")
    q = 1 - (1 - p) ** n
    return {
        "p": float(p), "n": n,
        "independent_any_slow": float(q),
        "equal_marginal_lower_bound": float(p),
        "equal_marginal_upper_bound": float(min(Fraction(1), n * p)),
        "independent_conditional_count": float(n * p / q) if q else None,
    }


def sample_summary(values):
    if not values or any(type(x) is not int or x < 0 for x in values):
        raise ValueError("use a nonempty list of nonnegative integer milliseconds")
    ordered = sorted(values)
    return {
        "observations": len(values),
        "mean_ms": float(Fraction(sum(values), len(values))),
        "p99_ms": ordered[ceil(Fraction(99, 100) * len(values)) - 1],
        "p999_ms": ordered[ceil(Fraction(999, 1000) * len(values)) - 1],
    }


def results():
    populations = [
        ("HDD", 458482, 38029, 857183442, 1885804, 72046373, 1109514),
        ("SSD", 4069, 572, 7481055, 43016, 1072690, 23964),
    ]
    observed = []
    for medium, drives, groups, drive_hours, slow_hours, group_hours, tail_hours in populations:
        observed.append({
            "medium": medium, "drives": drives, "groups": groups,
            "drive_hours": drive_hours, "slow_drive_hours": slow_hours,
            "group_hours": group_hours, "tail_group_hours": tail_hours,
            "slow_drive_hour_percent": float(Fraction(100 * slow_hours, drive_hours)),
            "tail_group_hour_percent": float(Fraction(100 * tail_hours, group_hours)),
            "slow_drives_per_tail_group_hour": float(Fraction(slow_hours, tail_hours)),
            "source": SOURCE, "locator": "Table 1, printed page 265",
        })
    return {
        "schemaVersion": 1,
        "generatedOn": REVIEW_DATE,
        "kind": "printed-count arithmetic and synthetic counterexamples",
        "sourceCodeSha256": sha256(Path(__file__).read_bytes()).hexdigest(),
        "runtime": "Python 3.12+ standard library; no random seed or third-party data",
        "observed_counts": observed,
        "fanout": [union_model(Fraction(1, 100), 100), union_model(Fraction(1, 10000), 2000)],
        "same_mean": [
            {"scenario": "Uniform", **sample_summary([10] * 1000)},
            {"scenario": "Bursty", **sample_summary([1] * 990 + [901] * 10)},
        ],
        "common_mode": [
            {"latencies_ms": [10, 10, 10], "ratios_to_group_median": [1, 1, 1]},
            {"latencies_ms": [100, 100, 100], "ratios_to_group_median": [1, 1, 1]},
        ],
        "limitations": [
            "No request traces or joint group histories were analyzed.",
            "Hourly co-classification is not necessarily simultaneous request delay.",
            "The conditional multiplicity is not a test of drive independence.",
            "Fanout examples require equal marginals, a fixed event and wait-for-all completion.",
            "Probability bounds permit arbitrary dependence, not an estimated confidence interval.",
            "Synthetic nearest-rank percentiles are examples, not observed device performance.",
            "No fleet confidence intervals are inferred from correlated aggregate counts.",
        ],
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(results(), indent=2) + "\n", encoding="utf-8")
