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=[]
def rd():
    for l in p.stdout: lines.append(l.strip())
threading.Thread(target=rd,daemon=True).start()
def wait(pred,to=30):
    d=time.monotonic()+to
    while time.monotonic()<d:
        if any(pred(l) for l in lines): return
        time.sleep(0.005)
wait(lambda l:"gen 1 hello" in l)
orig=open(SRC).read()
seen=[]
def ps():
    end=time.monotonic()+2
    while time.monotonic()<end:
        out=subprocess.run(["ps","-Ao","args"],capture_output=True,text=True).stdout
        for l in out.splitlines():
            if "rustc" in l and "--crate-name api " in l + " " and l not in seen:
                seen.append(l); return
        time.sleep(0.01)
open(SRC,"w").write(orig.replace("nested-v1","cap-1"))
ps()
time.sleep(3)
open(SRC,"w").write(orig)
time.sleep(0.4)
try: p.stdin.write("q\n");p.stdin.flush();p.wait(timeout=10)
except Exception: p.kill()
for l in seen: print(l)
