import json,os,shutil,subprocess,time,glob,collections
ROOT="/Users/oscar/.worktree/hot-reload/labs/hot-reload"; REC=f"{ROOT}/target/kan-hot/debug/rustc"
SRC=f"{ROOT}/api-common/src/lib.rs"; BASE="/private/var/folders/ft/fkt3bwqd01g7f54wvyz9wgjc0000gn/T/opencode/pipe/outP"
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 rewrite_extern(argv,name,path):
    out=[]; i=0
    while i<len(argv):
        a=argv[i]
        if a=="--extern" and i+1<len(argv) and argv[i+1].startswith(name+"="):
            out+=["--extern",f"{name}={path}"]; i+=2; continue
        if a.startswith(f"--extern={name}="): out.append(f"--extern={name}={path}"); 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); d=BASE
def run_api(extra=()):
    rmeta=os.path.join(d,[f for f in os.listdir(d) if f.startswith("libapi_common") and f.endswith(".rmeta")][0])
    aa=rewrite_extern([api["argv"][0]]+strip_owned(api["argv"]),"api_common",rmeta)
    aa+=["-C","debuginfo=0","-C","codegen-units=8","-C",f"incremental={BASE}/inc"]+list(extra)
    j=aa.index("--out-dir"); aa[j+1]=d
    env=dict(api["env"]); env["RUSTC_BOOTSTRAP"]="1"
    s=time.monotonic(); p=subprocess.run(aa,cwd=api["cwd"],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True); return (time.monotonic()-s)*1000,p
try:
    for i in range(3):
        open(SRC,"w").write(orig.replace("nested-v1",f"prof-{i}"))
        ca=[common["argv"][0]]+strip_owned(common["argv"])+["-C","debuginfo=0","-C","codegen-units=1"]
        j=ca.index("--out-dir"); ca[j+1]=d
        subprocess.run(ca,cwd=common["cwd"],env=dict(common["env"]),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        t,p=run_api(["-Zself-profile="+f"{BASE}/prof{i}"])
        print(f"iter {i}: {t:.1f}ms rc={p.returncode}")
    # aggregate last events
    ev=glob.glob(f"{BASE}/prof2/*.json")
    print("events files",ev)
    if ev:
        data=json.load(open(ev[0]))
        total=collections.Counter()
        for e in data:
            name=e.get("event"); 
            # events have 'start'/'end' (strings) maybe; use 'duration'?
            if "duration" in e: total[name]+=e["duration"]
            elif "start" in e and "end" in e:
                # timestamps in microseconds strings?
                pass
        for k,v in total.most_common(20): print(k,v)
        print("sample keys", list(data[0].keys()))
finally:
    open(SRC,"w").write(orig)
