#!/usr/bin/env python3
import os, subprocess, threading, time
LAB = "/Users/oscar/.worktree/hot-reload/labs/hot-reload"
CLI = "/Users/oscar/.worktree/hot-reload/target/debug/kan-hot-dev"
MANIFEST = os.path.join(LAB, "Cargo.toml")
original = open(MANIFEST).read()
env = dict(os.environ, RUST_LOG="info", KAN_HOT_TIMING="1", KAN_HOT_EXAMPLE_INTERVAL_MS="50")
p = subprocess.Popen([CLI, "run", "--bin", "server", "--lib", "api"], cwd=LAB,
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                     env=env, text=True, bufsize=1)
lines = []
lock = threading.Lock()
def reader():
    for line in p.stdout:
        with lock: lines.append(line.rstrip())
threading.Thread(target=reader, daemon=True).start()
def wait(pred, timeout=40):
    end = time.monotonic() + timeout
    while time.monotonic() < end:
        with lock:
            for l in reversed(lines):
                if pred(l): return True
        time.sleep(0.005)
    return False
try:
    assert wait(lambda l: "gen 1 hello" in l)
    open(MANIFEST, "a").write("\n# watcher test\n")
    ok = wait(lambda l: "shared/runtime code changed" in l)
    print("manifest edit triggered host rebuild:", ok)
    time.sleep(1.0)
    print("restart seen:", wait(lambda l: l.startswith("generation: 1"), timeout=10))
finally:
    open(MANIFEST, "w").write(original)
    time.sleep(0.3)
    try: p.stdin.write("q\n"); p.stdin.flush()
    except BrokenPipeError: pass
    try: p.wait(timeout=10)
    except subprocess.TimeoutExpired: p.kill()
