#!/usr/bin/env python3
"""Find the minimum CPU warm-up duty cycle that avoids the idle-wake penalty."""
import json, os, subprocess, time, statistics

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


def compile_():
    open(SRC, "w").write(orig.replace("nested-v1", f"x-{time.time_ns()}"))
    time.sleep(0.15)
    started = time.monotonic()
    p = subprocess.run(inv["argv"], cwd=inv["cwd"], env=dict(inv["env"]),
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    elapsed = (time.monotonic() - started) * 1000
    assert p.returncode == 0
    return elapsed


try:
    for duty, period in ((0, 0), (0.2, 20), (0.5, 20), (1, 20), (2, 20), (1, 10), (0.5, 10), (2, 50), (5, 50)):
        if warm:
            warm.kill()
            warm.wait()
            warm = None
        if duty:
            warm = subprocess.Popen(["/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/p4/warm",
                                     str(duty), str(period)],
                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            time.sleep(0.3)
        times = [compile_() for _ in range(6)]
        pct = 100 * duty / period if duty else 0
        print(f"duty={pct:5.1f}%  median={statistics.median(times):6.1f} mean={statistics.mean(times):6.1f} "
              f"min={min(times):6.1f} max={max(times):6.1f}")
finally:
    if warm:
        warm.kill()
        warm.wait()
    open(SRC, "w").write(orig)
