"""Swap rig A's daemon to the tip spt.exe under a SCRUBBED env (identity trio dropped), env read back."""
import os, subprocess, sys, time, pathlib
import psutil
TIP = r"C:\Users\decid\Documents\projects\spt-core\.worktrees\ws272-w2\target\debug\spt.exe"
HOME = r"C:\Users\decid\spt-rig-a"
TRIO = ("OWL_SESSION_ID", "SPT_AGENT_ID", "SPT_ENDPOINT_ID", "SPT_SESSION_NAME", "SPT_ADAPTER", "SPT_HOST_PID", "SPT_INJECT_VERIFY_ECHO", "SPT_POOL_UNCHECKED", "CARGO_TARGET_DIR")
env = dict(os.environ)
dropped = [k for k in TRIO if env.pop(k, None) is not None]
env["SPT_HOME"] = HOME
env["SPT_TEST_EPHEMERAL_ADVISORY_PORTS"] = "1"
env.pop("SPT_DOCS_PORT", None)
log = pathlib.Path(HOME) / "field-swap.log"
def run(*args, timeout=60):
    p = subprocess.run([TIP, *args], env=env, capture_output=True, text=True, timeout=timeout)
    out = (p.stdout + p.stderr).strip()
    log.open("a").write(f"[{time.strftime('%H:%M:%SZ', time.gmtime())}] {' '.join(args)} -> rc={p.returncode}\n{out}\n")
    return p.returncode, out
old_pid = int((pathlib.Path(HOME) / "daemon.pid").read_text().strip() or 0)
print(f"dropped={dropped} old_pid={old_pid} tip={TIP}")
rc, out = run("daemon", "stop")
print(f"daemon stop rc={rc}: {out[:300]}")
for _ in range(30):
    if not psutil.pid_exists(old_pid): break
    time.sleep(1)
print(f"old pid {old_pid} exists after stop: {psutil.pid_exists(old_pid)}")
if psutil.pid_exists(old_pid):
    print("REFUSED/STUCK: old daemon still alive; not starting a second one"); sys.exit(4)
rc, out = run("daemon", "run", "--detached", timeout=120)
print(f"daemon run --detached rc={rc}: {out[:300]}")
time.sleep(4)
new_pid = int((pathlib.Path(HOME) / "daemon.pid").read_text().strip() or 0)
try:
    pr = psutil.Process(new_pid); print(f"new pid {new_pid} exe={pr.exe()} env_SPT_HOME={pr.environ().get('SPT_HOME')} leaked={[k for k in TRIO if k in pr.environ()]}")
except Exception as e:
    print(f"new pid {new_pid} read-back failed: {e}")
rc, out = run("daemon", "status")
print(out[:600])
