import json, os, shutil, subprocess, time
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/out24"
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)
try:
    for label,stripped,incr,bootstrap in [("fresh-stripped",True,False,False),("fresh-stripped-boot",True,False,True),("fresh-raw",False,False,False),("fresh-raw-boot",False,False,True),("fresh-stripped-inc",True,True,False)]:
        d=f"{BASE}/{label}"; os.makedirs(d)
        mark=f"e24-{label}"
        open(SRC,"w").write(orig.replace("nested-v1",mark))
        base=[common["argv"][0]]+(strip_owned(common["argv"]) if stripped else common["argv"][1:])
        ca=base+["-C","debuginfo=0","-C","codegen-units=1"]
        if incr: ca+=["-C",f"incremental={d}/inc_common"]
        i=ca.index("--emit=dep-info,metadata,link"); ca[i]="--emit=metadata"
        j=ca.index("--out-dir"); ca[j+1]=d
        env=dict(common["env"])
        if bootstrap: env["RUSTC_BOOTSTRAP"]="1"
        p=subprocess.run(ca,cwd=common["cwd"],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        rmeta=os.path.join(d,[f for f in os.listdir(d) if 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={d}/inc_api"]
        j=aa.index("--out-dir"); aa[j+1]=d
        env2=dict(api["env"])
        if bootstrap: env2["RUSTC_BOOTSTRAP"]="1"
        p2=subprocess.run(aa,cwd=api["cwd"],env=env2,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
        print(label,"common_rc",p.returncode,"api_rc",p2.returncode, "err", [l[:140] for l in p2.stderr.decode(errors="replace").splitlines() if 'error' in l.lower()][:2])
finally:
    open(SRC,"w").write(orig)
