import json, os, shutil, subprocess, time

ROOT="/Users/oscar/.worktree/hot-reload/labs/hot-reload"
REC=f"{ROOT}/target/kan-hot/debug/rustc"
SCRATCH="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/pipe/out5"
SRC=f"{ROOT}/api-common/src/lib.rs"
INC=f"{ROOT}/target/kan-hot/debug/incremental/api"
DEPS=f"{ROOT}/target/debug/deps"
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 cmd(d, name, tiny, outdir, inc):
    argv=[d["argv"][0]]+strip_owned(d["argv"])
    cu=1 if tiny else 8
    argv+=["-C","debuginfo=0","-C",f"codegen-units={cu}"]
    if inc: argv+=["-C",f"incremental={inc}"]
    i=argv.index("--out-dir"); argv[i+1]=outdir
    return argv
common=load("api_common"); api=load("api")
orig=open(SRC).read()
shutil.rmtree(SCRATCH,ignore_errors=True); os.makedirs(SCRATCH)
try:
    for i in range(5):
        open(SRC,"w").write(orig.replace("nested-v1",f"e5-{i}"))
        t=time.monotonic()
        p=subprocess.run(cmd(common,"api_common",True,DEPS,f"{ROOT}/target/kan-hot/debug/incremental/api_common"),cwd=common["cwd"],env=env_of(common),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        tc=(time.monotonic()-t)*1000
        t=time.monotonic()
        p2=subprocess.run(cmd(api,"api",False,DEPS,INC),cwd=api["cwd"],env=env_of(api),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        ta=(time.monotonic()-t)*1000
        print(f"common={tc:.1f} api={ta:.1f} rc={p.returncode}/{p2.returncode}")
        time.sleep(0.15)
finally:
    open(SRC,"w").write(orig)
