import json, os, shutil, subprocess, time, sys
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"
BASE="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/pipe/outS"
def load(n): return json.load(open(f"{REC}/{n}.json"))
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
common=load("api_common"); api=load("api"); orig=open(SRC).read(); assert "nested-v1" in orig
shutil.rmtree(BASE,ignore_errors=True); os.makedirs(BASE)
def comp(i,warm):
    open(SRC,"w").write(orig.replace("nested-v1",f"sm-{i}"))
    ca=[common["argv"][0]]+strip_owned(common["argv"])+["-C","debuginfo=0","-C","codegen-units=1"]
    j=ca.index("--out-dir"); ca[j+1]=DEPS
    subprocess.run(ca,cwd=common["cwd"],env=dict(common["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    raw=[api["argv"][0]]+strip_owned(api["argv"])+["-C","debuginfo=0","-C","codegen-units=8","-C",f"incremental={BASE}/inc"]
    j=raw.index("--out-dir"); raw[j+1]=DEPS
    t=time.monotonic(); p=subprocess.Popen(raw,cwd=api["cwd"],env=dict(api["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    return p,t
try:
    for i in range(4): p,t=comp(i,True); p.wait(); time.sleep(.1)
    p,t=comp(10,False)
    time.sleep(0.01)
    print("pid",p.pid)
    subprocess.run(["sample",str(p.pid),"1","-file",f"{BASE}/sample.txt","-mayDie"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    p.wait(); print("api", (time.monotonic()-t)*1000)
finally:
    open(SRC,"w").write(orig)
