#!/usr/bin/env python3
import os, subprocess, time, statistics, shlex

LAB = "/Users/oscar/.worktree/hot-reload/labs/hot-reload"
SRC = os.path.join(LAB, "api-common/src/lib.rs")
WRAPPER = "/Users/oscar/.worktree/hot-reload/target/debug/kan-hot-dev"
TLIB = subprocess.check_output(["rustc", "--print", "target-libdir"], text=True).strip()
BASE = dict(
    os.environ,
    RUSTC_WORKSPACE_WRAPPER=WRAPPER,
    KAN_HOT_WRAPPER_HOST="server",
    KAN_HOT_WRAPPER_HOT="api,api_common",
    KAN_HOT_RUNTIME_LIBS_FILE="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/link-exp/runtime.txt",
    KAN_HOT_TARGET_LIBDIR=TLIB,
)
original = open(SRC).read()

open(SRC, "w").write(original.replace("nested-v1", "nested-c2"))
p = subprocess.run(["cargo", "build", "-p", "api", "-p", "server", "--lib", "-v"],
                   cwd=LAB, env=BASE, text=True, capture_output=True)
open(SRC, "w").write(original)
cmds = {}
for line in p.stderr.splitlines():
    if "Running" not in line or "--crate-name" not in line:
        continue
    body = line.split("Running `", 1)[1].rsplit("`", 1)[0]
    argv = shlex.split(body)
    if argv[0] == "kache":
        argv = argv[1:]
    name = argv[argv.index("--crate-name") + 1]
    cmds[name] = argv

variants = {
    "default": [],
    "cgu1": ["-C", "codegen-units=1"],
    "cgu16": ["-C", "codegen-units=16"],
    "prefer_dyn": ["-C", "prefer-dynamic"],
    "no_inc": ["-C", "incremental=off"],
    "cgu1_no_inc": ["-C", "codegen-units=1", "-C", "incremental=off"],
    "cgu16_no_inc": ["-C", "codegen-units=16", "-C", "incremental=off"],
}
results = {k: [] for k in variants}
for rep in range(4):
    for idx, (name, extra) in enumerate(variants.items()):
        marker = "nested-" + f"{rep * len(variants) + idx:02x}"
        open(SRC, "w").write(original.replace("nested-v1", marker))
        start = time.monotonic()
        for crate in ("api_common", "api"):
            r = subprocess.run(cmds[crate] + extra, cwd=LAB, env=BASE,
                               stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            if r.returncode != 0:
                print(name, crate, r.stderr.decode()[:1200]); raise SystemExit(1)
        results[name].append((time.monotonic() - start) * 1000)
open(SRC, "w").write(original)
for name, vals in results.items():
    print(f"{name:14} median={statistics.median(vals):6.1f} mean={statistics.mean(vals):6.1f} {[round(v) for v in vals]}")
