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/out6"
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, stripped, outdir, inc):
    argv=[d["argv"][0]]+(strip_owned(d["argv"]) if stripped else d["argv"][1:])
    if stripped: argv+=["-C","debuginfo=0","-C","codegen-units=8","-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 variant in ["raw","stripped"]:
        for outdir_name,outdir in [("deps",DEPS),("scratch",SCRATCH)]:
            print("===",variant,outdir_name)
            for i in range(3):
                open(SRC,"w").write(orig.replace("nested-v1",f"e6-{variant}-{outdir_name}-{i}"))
                # compile common exactly as replay does, into DEPS, so rmeta path matches recording
                s=time.monotonic(); subprocess.run(cmd(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); t1=(time.monotonic()-s)*1000
                s=time.monotonic(); p=subprocess.run(cmd(api,variant=="stripped",outdir,INC),cwd=api["cwd"],env=env_of(api),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); t2=(time.monotonic()-s)*1000
                print(f" common={t1:.1f} api={t2:.1f} rc={p.returncode}")
                time.sleep(0.15)
finally:
    open(SRC,"w").write(orig)
