import os,subprocess,time,threading
ROOT="/Users/oscar/.worktree/hot-reload/labs/hot-reload"; CLI="/Users/oscar/.worktree/hot-reload/target/debug/kan-hot-dev"
SRC=os.path.join(ROOT,"api-common","src","lib.rs")
env=dict(os.environ,RUST_LOG="error",KAN_HOT_TIMING="1",KAN_HOT_EXAMPLE_INTERVAL_MS="1000")
p=subprocess.Popen([CLI,"run","--bin","server","--lib","api"],cwd=ROOT,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,env=env,text=True,bufsize=1)
lines=[]; lock=threading.Lock()
def rd():
    for l in p.stdout:
        with lock: lines.append((time.monotonic(),l.rstrip()))
threading.Thread(target=rd,daemon=True).start()
def wait(pred,to=30):
    d=time.monotonic()+to
    while time.monotonic()<d:
        with lock:
            for t,l in lines:
                if pred(l): return t,l
        time.sleep(.001)
    raise TimeoutError
wait(lambda l:"gen 1 hello" in l)
orig=open(SRC).read()
try:
    for i in range(3):
        mark=f"tl-{i}-{time.time_ns()}"
        with lock: before=len(lines)
        open(SRC,"w").write(orig.replace("nested-v1",mark)); t0=time.monotonic()
        t,l=wait(lambda l,m=mark: f'"nested":"{m}"' in l)
        print(f"--- edit {i}: total {1000*(t-t0):.2f}ms")
        with lock: recent=lines[before:]
        for ts,line in recent:
            if any(k in line for k in ("change detected","replay","thin link","cargo hot","reloaded","loaded generation","gen ")) or '"nested"' in line:
                print(f"  +{1000*(ts-t0):7.2f}  {line[:110]}")
        time.sleep(0.8)
finally:
    open(SRC,"w").write(orig); time.sleep(.4)
    try: p.stdin.write("q\n");p.stdin.flush();p.wait(timeout=10)
    except Exception: p.kill()
