import json, os, shutil, subprocess, time, glob
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/out16"
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 measure(name,outdir,iters=4,clean=False,precreate=False):
    os.makedirs(outdir,exist_ok=True)
    if precreate:
        for i in range(1000): open(os.path.join(outdir,f"x{i}.rlib"),"wb").write(b"x"*10)
    inc=f"{BASE}/inc_{name}"
    print("===",name,outdir)
    for i in range(iters):
        if clean:
            for pat in ["libapi-*","api-*.d"]:
                for f in glob.glob(os.path.join(outdir,pat)): os.remove(f)
        open(SRC,"w").write(orig.replace("nested-v1",f"e16-{name}-{i}"))
        ca=[common["argv"][0]]+strip_owned(common["argv"])+["-C","debuginfo=0","-C","codegen-units=1"]
        j=ca.index("--out-dir"); ca[j+1]=outdir
        s=time.monotonic(); pc=subprocess.run(ca,cwd=common["cwd"],env=dict(common["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); tc=(time.monotonic()-s)*1000
        rmeta=os.path.join(outdir,[f for f in os.listdir(outdir) if f.startswith("libapi_common") and f.endswith(".rmeta")][0])
        raw=[api["argv"][0]]+[a if not a.startswith("--extern=api_common=") else f"--extern=api_common={rmeta}" for a in api["argv"][1:]]
        aa=[api["argv"][0]]+strip_owned(raw)+["-C","debuginfo=0","-C","codegen-units=8","-C",f"incremental={inc}"]
        j=aa.index("--out-dir"); aa[j+1]=outdir
        s=time.monotonic(); pa=subprocess.run(aa,cwd=api["cwd"],env=dict(api["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); ta=(time.monotonic()-s)*1000
        print(f" {i}: common={tc:.1f} api={ta:.1f} rc={pc.returncode}/{pa.returncode}")
        time.sleep(.15)
try:
    measure("deps_clean",DEPS,clean=True)
    measure("debug_empty",f"{ROOT}/target/debug/emptydir")
    measure("deps_sub",f"{DEPS}/subdir")
    measure("kanhot_empty",f"{ROOT}/target/kan-hot/debug/emptydir")
    measure("deps_copy",f"{BASE}/deps_copy")
finally:
    open(SRC,"w").write(orig)
