import json, os, shutil, subprocess, time
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"
SCRATCH="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/pipe/out9"
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
def set_out(argv,d):
    i=argv.index("--out-dir"); argv[i+1]=d; return argv
common=load("api_common"); api=load("api"); orig=open(SRC).read()
shutil.rmtree(SCRATCH,ignore_errors=True); os.makedirs(SCRATCH)
try:
    for outname,outdir in [("deps",DEPS),("scratch",SCRATCH)]:
        print("===",outname)
        for i in range(4):
            open(SRC,"w").write(orig.replace("nested-v1",f"e9-{outname}-{i}"))
            ca=set_out([common["argv"][0]]+strip_owned(common["argv"])+["-C","debuginfo=0","-C","codegen-units=1"],outdir if outname=="scratch" else DEPS)
            s=time.monotonic(); 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 if outname=="scratch" else DEPS,[f for f in os.listdir(outdir if outname=="scratch" else DEPS) 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={SCRATCH}/inc_api"]
            aa=set_out(aa,outdir)
            s=time.monotonic(); p=subprocess.run(aa,cwd=api["cwd"],env=dict(api["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); ta=(time.monotonic()-s)*1000
            print(f" common={tc:.1f} api={ta:.1f} rc={p.returncode}")
            time.sleep(0.15)
finally:
    open(SRC,"w").write(orig)
