import json, os, shutil, subprocess, time, sys

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/out4"
SRC=f"{ROOT}/api-common/src/lib.rs"
REALINC=f"{ROOT}/target/kan-hot/debug/incremental/api"
def load(n): return json.load(open(f"{REC}/{n}.json"))
def env_of(d):
    e=dict(d["env"]); e["PATH"]=os.environ["PATH"]; return e
common=load("api_common"); api=load("api")
shutil.rmtree(SCRATCH,ignore_errors=True); os.makedirs(SCRATCH)
orig=open(SRC).read()

def api_with(inc, rmeta, runs):
    out=[]; j=0
    while j<len(api["argv"]):
        a=api["argv"][j]
        if a.startswith("--extern=api_common="): out.append(f"--extern=api_common={rmeta}")
        elif a=="-C" and j+1<len(api["argv"]) and api["argv"][j+1].startswith("incremental="):
            out+=["-C",f"incremental={inc}"]; j+=1
        else: out.append(a)
        j+=1
    i=out.index("--out-dir"); out[i+1]=SCRATCH
    res=[]
    for _ in range(runs):
        t=time.monotonic(); p=subprocess.run(out,cwd=api["cwd"],env=env_of(api),capture_output=True,text=True)
        res.append(((time.monotonic()-t)*1000,p.returncode))
    return res

try:
    for variant in ["real","fresh"]:
        inc=f"{SCRATCH}/inc_{variant}"
        shutil.rmtree(inc,ignore_errors=True)
        if variant=="real": shutil.copytree(REALINC,inc)
        print("===",variant)
        for i in range(4):
            open(SRC,"w").write(orig.replace("nested-v1",f"e4-{variant}-{i}"))
            argv=list(common["argv"]); j=argv.index("--out-dir"); argv[j+1]=SCRATCH
            # remove old rmeta
            for f in os.listdir(SCRATCH):
                if f.endswith(".rmeta"): os.remove(os.path.join(SCRATCH,f))
            t=time.monotonic(); pc=subprocess.run(argv,cwd=common["cwd"],env=env_of(common),capture_output=True,text=True); tc=(time.monotonic()-t)*1000
            rmeta=os.path.join(SCRATCH,[f for f in os.listdir(SCRATCH) if f.endswith(".rmeta")][0])
            r=api_with(inc,rmeta,1)
            print(f" common={tc:.1f} api={r[0][0]:.1f} rc={r[0][1]}")
            time.sleep(0.2)
finally:
    open(SRC,"w").write(orig)
