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/out21"
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)
FRESH=f"{BASE}/fresh"; os.makedirs(FRESH)
# variants: name, common_out, api_out, rmeta_mode
variants=[("ff",FRESH,FRESH,"same"),("dd",DEPS,DEPS,"same"),("fd",FRESH,DEPS,"same"),("df",DEPS,FRESH,"same"),("f_copycanon",FRESH,FRESH,"copycanon"),("f_copyuniq",FRESH,FRESH,"copyuniq")]
incs={v[0]:f"{BASE}/inc_{v[0]}" for v in variants}
def run(variant,i):
    name,cout,aout,mode=variant
    open(SRC,"w").write(orig.replace("nested-v1",f"e21-{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]=cout
    sc=time.monotonic(); pc=subprocess.run(ca,cwd=common["cwd"],env=dict(common["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); tc=(time.monotonic()-sc)*1000
    src=os.path.join(cout,[f for f in os.listdir(cout) if f.startswith("libapi_common") and f.endswith(".rmeta")][0])
    if mode=="copycanon":
        dst=os.path.join(DEPS,os.path.basename(src)); shutil.copy(src,dst); rmeta=dst
    elif mode=="copyuniq":
        dst=os.path.join(DEPS,"libapi_common-uniq.rmeta"); shutil.copy(src,dst); rmeta=dst
    else:
        rmeta=src
    os.makedirs(aout,exist_ok=True)
    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={incs[name]}"]
    j=aa.index("--out-dir"); aa[j+1]=aout
    s=time.monotonic(); pa=subprocess.run(aa,cwd=api["cwd"],env=dict(api["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); return (time.monotonic()-s)*1000,pc.returncode,pa.returncode
try:
    rounds=5
    # warm all
    for v in variants: run(v,99)
    time.sleep(.3)
    results={v[0]:[] for v in variants}
    for i in range(rounds):
        for v in variants:
            t,rc1,rc2=run(v,i)
            results[v[0]].append(t)
            time.sleep(.12)
    for k,vs in results.items():
        print(k, [f"{x:.1f}" for x in vs], "median", sorted(vs)[len(vs)//2])
finally:
    open(SRC,"w").write(orig)
