#!/usr/bin/env python3
"""Real Codex goal restart proof helper. Run from either tested checkout.
Start the app separately with T3CODE_DEV_SEED=0 vp run dev.
seed WORKSPACE adds synthetic data and starts the exact proof goal.
restart PORT verifies the port owner's cwd, stops that server, then wakes its dev watcher.
inspect THREAD prints only synthetic messages and goal status.
Pair the browser using that server's startup URL. Open the returned thread,
hide sidebar and details, record before restart until the child wakes the parent.
"""
import json, pathlib, subprocess, sys, sqlite3, os, signal
PROMPT = """/goal Prove goal continuation across delegated work. First call orchestrator_capabilities, then delegate_task in async mode to the Codex provider using gpt-6.1-sol with this task: run a shell command that waits 180 seconds, then reply CHILD_READY. Do not do the child work yourself. After delegation, immediately end your parent turn with WAITING_FOR_CHILD, following the delegated next instruction; do not wait or poll. After receiving the child result in a later turn, reply STAGE_ONE and end that turn immediately without completing the goal. On the next automatic goal continuation turn, reply STAGE_TWO and mark the goal complete. These separate turns are required by this goal. Do not complete the goal during STAGE_ONE."""

def cli(*args):
    return subprocess.check_output(["node", "apps/server/src/bin.ts", *args], text=True)

if sys.argv[1] == "seed":
    workspace = pathlib.Path(sys.argv[2]).resolve()
    workspace.mkdir(parents=True, exist_ok=True)
    print(cli("project", "add", "--base-dir", ".t3", "--title", "Goal restart proof", str(workspace)))
    print(cli("thread", "start", "--base-dir", ".t3", "--provider", "codex", "--model", "gpt-6.1-sol", "--option", "reasoningEffort=low", "--title", "Delegated goal restart", str(workspace), PROMPT, "--json"))
elif sys.argv[1] == "restart":
    import re
    line = subprocess.check_output(["ss", "-H", "-ltnp", "sport = :" + sys.argv[2]], text=True)
    pid = int(re.search(r"pid=(\d+)", line)[1])
    assert pathlib.Path(f"/proc/{pid}/cwd").resolve() == pathlib.Path("apps/server").resolve()
    os.kill(pid, signal.SIGTERM)
    pathlib.Path("apps/server/src/bin.ts").touch()
elif sys.argv[1] == "inspect":
    tid = sys.argv[2]
    state = json.loads(cli("thread", "show", "--base-dir", ".t3", tid, "--json"))
    db = sqlite3.connect("file:.t3/userdata/statev2.sqlite?mode=ro", uri=True)
    goal = db.execute("SELECT json_extract(payload_json, '$.goal') FROM orchestration_v2_projection_provider_threads WHERE thread_id=?", (tid,)).fetchone()
    print(json.dumps({"status": state["thread"]["status"], "messages": [{"role": x["role"], "text": x["text"]} for x in state["messages"]], "goal": json.loads(goal[0]) if goal and goal[0] else None}, indent=2))

elif sys.argv[1] == "control-seed":
    case, workspace = sys.argv[2], str(pathlib.Path(sys.argv[3]).resolve())
    prompt = pathlib.Path(__file__).with_name(case + "-prompt.txt").read_text()
    print(cli("thread", "start", "--base-dir", ".t3", "--provider", "codex", "--model", "gpt-6.1-sol", "--option", "reasoningEffort=low", "--title", case.title() + " goal control", workspace, prompt, "--json"))
elif sys.argv[1] == "pause":
    print(cli("thread", "send", "--base-dir", ".t3", sys.argv[2], "/goal pause", "--json"))
elif sys.argv[1] == "audit":
    n = sys.argv[3]
    if n == "2":
        prompt = "This is the second consecutive turn auditing the same missing external approval. That approval remains unavailable. Do not create another child or complete the goal. Assess the same blocker and end this turn."
    elif n == "3":
        prompt = "This is the third consecutive goal turn with the same missing external approval. It remains unavailable. Now call update_goal status blocked, then end this turn. Do not create a child, do not wait, and do not complete the goal."
    else:
        raise ValueError("audit must be 2 or 3")
    print(cli("thread", "send", "--base-dir", ".t3", sys.argv[2], prompt, "--json"))
