#!/usr/bin/env python3
"""Test whether the idle gap before a compile changes its duration."""
import json, os, subprocess, time, statistics

REC = "/Users/oscar/.worktree/hot-reload/labs/hot-reload/target/kan-hot/debug/rustc"
SRC = "/Users/oscar/.worktree/hot-reload/labs/hot-reload/api-common/src/lib.rs"
inv = json.load(open(os.path.join(REC, "api_common.json")))


def once(marker):
    original = open(SRC).read()
    open(SRC, "w").write(original.replace("nested-v1", marker))
    started = time.monotonic()
    p = subprocess.run(inv["argv"], cwd=inv["cwd"], env=dict(inv["env"]),
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    assert p.returncode == 0
    return (time.monotonic() - started) * 1000


for gap in (0.0, 0.05, 0.15, 0.5, 1.0):
    times = []
    for i in range(8):
        time.sleep(gap)
        times.append(once(f"gap-{gap}-{i}-{time.time_ns()}"))
    print(f"gap={gap:4.2f}s median={statistics.median(times):6.1f} mean={statistics.mean(times):6.1f} min={min(times):6.1f} max={max(times):6.1f}")
