import json, os, shutil, subprocess, time
ROOT="/Users/oscar/.worktree/hot-reload/labs/hot-reload"; REC=f"{ROOT}/target/kan-hot/debug/rustc"
DEPS=f"{ROOT}/target/debug/deps"; SRC=f"{ROOT}/api-common/src/lib.rs"
SCRATCH="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/pipe/out8"
def load(n): return json.load(open(f"{REC}/{n}.json"))
def env_of(d): return dict(d["env"])
def strip_owned(argv):
    out=[]; i=1
    while i<len(argv):
        a=argv[i]
        if a=="-C" and i+1<len(argv) and any(argv[i+1].startswith(p) for p in ("incremental=","codegen-units=","debuginfo=")): i+=2; continue
        if a.startswith("-C") and any(a[2:].startswith(p) for p in ("incremental=","codegen-units=","debuginfo=")): i+=1; continue
        out.append(a); i+=1
    return out
def common_cmd():
    return [common["argv"][0]]+strip_owned(common["argv"])+["-C","debuginfo=0","-C","codegen-units=1"]
def api_cmd(inc):
    return [api["argv"][0]]+strip_owned(api["argv"])+["-C","debuginfo=0","-C","codegen-units=8","-C",f"incremental={inc}"]
def size(d):
    return sum(os.path.getsize(os.path.join(dp,f)) for dp,_,fs in os.walk(d) for f in fs)
common=load("api_common"); api=load("api"); orig=open(SRC).read()
shutil.rmtree(SCRATCH,ignore_errors=True); os.makedirs(SCRATCH)
inc=f"{SCRATCH}/inc"; 
try:
    for i in range(14):
        open(SRC,"w").write(orig.replace("nested-v1",f"e8-{i}"))
        s=time.monotonic(); subprocess.run(common_cmd(),cwd=common["cwd"],env=env_of(common),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); tc=(time.monotonic()-s)*1000
        s=time.monotonic(); p=subprocess.run(api_cmd(inc),cwd=api["cwd"],env=env_of(api),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); ta=(time.monotonic()-s)*1000
        print(f"{i}: common={tc:.1f} api={ta:.1f} cache={size(inc)/1e6:.1f}MB rc={p.returncode}")
        time.sleep(0.15)
finally:
    open(SRC,"w").write(orig)
