#!/usr/bin/env python3
"""Real OpenCode 2.3.0 goal/restart-sweep reproduction (no mocked protocol).
Usage: driver.py WORKTREE RUN_DIRECTORY OPENCODE_BINARY configure|seed|control|repro|sweep|status [THREAD_ID]
T3 must run with T3CODE_DEV_SEED=0, its own .t3 home, and provider-only XDG dirs
under RUN_DIRECTORY. Copy only provider configuration, never user sessions.
"""
import sys, pathlib, subprocess, json, os, sqlite3
wt, run, binary = map(pathlib.Path, sys.argv[1:4])
action = sys.argv[4]
project = run / "goal-demo"
def cli(*args):
    return subprocess.check_output(["node", "apps/server/src/bin.ts", *args,
                                   "--base-dir", str(wt / ".t3")], cwd=wt, text=True)
if action == "configure":
    # Run before starting T3; pass the provider configuration file as the last argument.
    provider = json.loads(pathlib.Path(sys.argv[5]).read_text())["provider"]
    cfg = run / "config/opencode"
    cfg.mkdir(parents=True, exist_ok=True)
    (cfg / "opencode.json").write_text(json.dumps({"provider": provider}))
    env = [{"name": "XDG_" + key.upper() + "_HOME", "value": str(run / key)}
           for key in ["config", "data", "state", "cache"]]
    settings = wt / ".t3/userdata/settings.json"
    settings.parent.mkdir(parents=True, exist_ok=True)
    settings.write_text(json.dumps({"providerInstances": {"opencode": {
        "driver": "opencode", "enabled": True,
        "config": {"binaryPath": str(binary)}, "environment": env}}}))
    print("Isolated provider configured")
elif action == "seed":
    project.mkdir(parents=True, exist_ok=True)
    (project / "README.md").write_text("Synthetic goal recovery reproduction.\n")
    for args in [["init", "-q", "-b", "main"], ["add", "README.md"],
                 ["-c", "user.name=Evidence", "-c", "user.email=evidence@example.invalid",
                  "commit", "-qm", "Initial commit"]]:
        subprocess.run(["git", *args], cwd=project, check=True)
    cli("project", "add", str(project), "--title", "Goal recovery demo")
    print("Project created")
elif action in ["control", "repro"]:
    seconds, step, final = (75, "step1.txt", "final.txt") if action == "control" else (90, "step2.txt", "final2.txt")
    prompt = f"/goal Run `sleep {seconds} && echo DONE > {step}` in the foreground, wait for it to finish, then create {final} containing DONE. Do not background the command. The goal is complete only when both files exist."
    result = json.loads(cli("thread", "start", "--provider", "opencode", "--model",
                           "anthropic/claude-haiku-5-5", "--title",
                           "Control goal" if action == "control" else "Restart sweep goal",
                           "--json", str(project), prompt))
    (run / (action + "-thread.json")).write_text(json.dumps(result))
    print(json.dumps(result))
elif action == "sweep":
    env = dict(os.environ)
    for key in ["config", "data", "state", "cache"]:
        env["XDG_" + key.upper() + "_HOME"] = str(run / key)
    subprocess.run([str(binary), "run", "-m", "anthropic/claude-haiku-5-5",
                    "Reply with the single word hi."], cwd=project, env=env, check=True,
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    print("Second OpenCode process finished")
elif action == "status":
    thread_id = sys.argv[5]
    t = json.loads(cli("thread", "show", thread_id, "--json"))["thread"]
    db = sqlite3.connect(f"file:{run / 'data/opencode/opencode.db'}?mode=ro", uri=True)
    goals = [json.loads(row[0]) for row in db.execute("select value from kv where key like 'plugin:%'")]
    print(json.dumps({"t3Status": t["status"], "activeRun": t["activeRunId"] is not None,
                      "goals": [{k:g.get(k) for k in ["objective", "status", "reason"]} for g in goals],
                      "nativeSessions": list(db.execute("select time_idle,idle_outcome from session_v2")),
                      "jobs": db.execute("select count(*) from job").fetchone()[0],
                      "files": {f:(project/f).read_text() if (project/f).exists() else None
                                for f in ["step1.txt", "final.txt", "step2.txt", "final2.txt"]}}, indent=2))
