import json, os, shutil, subprocess, time, hashlib
ROOT="/Users/oscar/.worktree/hot-reload/labs/hot-reload"
REC=f"{ROOT}/target/kan-hot/debug/rustc"
DEPS=f"{ROOT}/target/debug/deps"; INC=f"{ROOT}/target/kan-hot/debug/incremental/api"; SRC=f"{ROOT}/api-common/src/lib.rs"
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 common_cmd(mode):
    argv=[common["argv"][0]]+strip_owned(common["argv"])
    if mode=="raw": argv=[common["argv"][0]]+common["argv"][1:]
    elif mode=="stripped": argv+=["-C","debuginfo=0","-C","codegen-units=1"]
    elif mode=="stripped_inc": argv+=["-C","debuginfo=0","-C","codegen-units=1","-C",f"incremental={ROOT}/target/kan-hot/debug/incremental/api_common"]
    elif mode=="stripped_cgu8": argv+=["-C","debuginfo=0","-C","codegen-units=8"]
    return argv
def api_cmd():
    argv=[api["argv"][0]]+strip_owned(api["argv"])
    argv+=["-C","debuginfo=0","-C","codegen-units=8","-C",f"incremental={INC}"]
    return argv
common=load("api_common"); api=load("api")
orig=open(SRC).read()
rmeta=None
try:
    for mode in ["stripped","raw","stripped_inc","stripped_cgu8"]:
        print("===",mode)
        for i in range(3):
            open(SRC,"w").write(orig.replace("nested-v1",f"e7-{mode}-{i}"))
            s=time.monotonic(); p=subprocess.run(common_cmd(mode),cwd=common["cwd"],env=env_of(common),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); tc=(time.monotonic()-s)*1000
            rmeta=[os.path.join(DEPS,f) for f in os.listdir(DEPS) if f.startswith("libapi_common") and f.endswith(".rmeta")][0]
            size=os.path.getsize(rmeta)
            s=time.monotonic(); p2=subprocess.run(api_cmd(),cwd=api["cwd"],env=env_of(api),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL); ta=(time.monotonic()-s)*1000
            print(f" common={tc:.1f} api={ta:.1f} rmeta={size} rc={p.returncode}/{p2.returncode}")
            time.sleep(0.15)
finally:
    open(SRC,"w").write(orig)
