import os,subprocess,time,threading,sys
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")
extra=dict(x.split("=",1) for x in sys.argv[1:])
env=dict(os.environ,RUST_LOG="error",KAN_HOT_TIMING="1",KAN_HOT_EXAMPLE_INTERVAL_MS="50"); env.update(extra)
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=[]
def rd():
    for l in p.stdout: lines.append((time.monotonic(),l.strip()))
threading.Thread(target=rd,daemon=True).start()
def wait(pred,to=30):
    d=time.monotonic()+to
    while time.monotonic()<d:
        for t,l in lines:
            if pred(l): return t,l
        time.sleep(0.005)
    raise TimeoutError
wait(lambda l:"gen 1 hello" in l)
orig=open(SRC).read()
try:
    for i in range(4):
        mark=f"m-{os.getpid()}-{i}-{time.time_ns()}"
        open(SRC,"w").write(orig.replace("nested-v1",mark))
        t0=time.monotonic()
        wait(lambda l,m=mark: f'"nested":"{m}"' in l)
        print(f"E2E {1000*(time.monotonic()-t0):.1f}ms")
        time.sleep(0.5)
finally:
    open(SRC,"w").write(orig)
    time.sleep(0.5)
    try: p.stdin.write("q\n");p.stdin.flush();p.wait(timeout=10)
    except Exception: p.kill()
for t,l in lines:
    if "replay api " in l or "replay api_common" in l: print(l)
