#!/usr/bin/env python3
"""Scratch driver for the real-app Claude startup retry reproduction.
Run from an isolated checkout with its dev server and fresh .t3 state.
init configures the symlink, creates the synthetic project, and sends the first prompt.
After init, open the returned thread in the browser, dismiss banners and collapse
navigation/details, begin recording, run restore, and send the identical prompt.
The failing executable intentionally emits no provider protocol or model reply.
"""
import argparse, json, os, sqlite3, subprocess
from pathlib import Path
from datetime import datetime, timezone
p=argparse.ArgumentParser()
p.add_argument("stage",choices=["init","restore","checkpoint","restart"])
p.add_argument("--scratch",type=Path,required=True)
p.add_argument("--side",choices=["base","head"],required=True)
p.add_argument("--real-cli",type=Path)
p.add_argument("--thread")
a=p.parse_args(); root=a.scratch.resolve(); root.mkdir(parents=True,exist_ok=True)
link=root/("claude-"+a.side)
def cli(*args):
    return subprocess.check_output(["node","apps/server/src/bin.ts",*args],text=True)
if a.stage=="init":
    failure=root/"startup-failure.sh"
    failure.write_text('#!/bin/sh\necho "Controlled startup failure before system:init" >&2\nexit 1\n')
    failure.chmod(0o755)
    if link.is_symlink(): link.unlink()
    link.symlink_to(failure)
    settings=Path(".t3/userdata/settings.json")
    data=json.loads(settings.read_text())
    data.setdefault("providerInstances",{})["claude"]={"driver":"claudeAgent","enabled":True,"config":{"binaryPath":str(link)}}
    settings.write_text(json.dumps(data,indent=2))
    workspace=root/"workspace";workspace.mkdir(exist_ok=True)
    print(cli("project","add","--base-dir",".t3","--title","Claude startup retry",str(workspace)))
    print(cli("thread","start","--base-dir",".t3","--provider","claude","--model","haiku","--title","Claude retry proof","--json",str(workspace),"Reply with RETRY_OK and nothing else"))
elif a.stage=="restore":
    if not a.real_cli: p.error("--real-cli required")
    if link.is_symlink():link.unlink()
    link.symlink_to(a.real_cli.resolve())
elif a.stage=="checkpoint":
    if not a.thread:p.error("--thread required")
    db=sqlite3.connect("file:"+str(Path(".t3/userdata/statev2.sqlite").resolve())+"?mode=ro",uri=True)
    rows=db.execute("select provider_session_id,status,payload_json from orchestration_v2_projection_provider_threads where thread_id=?",(a.thread,)).fetchall()
    result={"side":a.side,"commit":subprocess.check_output(["git","rev-parse","HEAD"],text=True).strip(),"sessions":[{"sessionId":sid,"status":status,"resumeCursor":json.loads(payload).get("resumeCursor")} for sid,status,payload in rows]}
    state=json.loads(cli("thread","show","--base-dir",".t3","--json",a.thread))
    result.update(status=state["thread"]["status"],messages=state["messages"],error=state.get("error"))
    out=root/(a.side+"-"+datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%f")+".json")
    out.write_text(json.dumps(result,indent=2));print(out)
elif a.stage=="restart":
    # The dev watch launcher terminates and starts a new server process on touch.
    os.utime("apps/server/src/bin.ts",None)
