"""Run from a prepared evidence worktree, with its dev server already running.
Usage: python seed-and-inspect.py seed <scratch> <base|head>
       python seed-and-inspect.py inspect <thread-id>
Start both servers with T3CODE_DEV_SEED=0 vp run dev.
Start limit-proxy.mjs once with its JSONL log path as argument.
Open the returned thread in the web app, collapse sidebar and details,
record, click Resume thread exactly once, and inspect after it stops.
"""
import json, pathlib, subprocess, sys, sqlite3

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

if sys.argv[1]=='seed':
    scratch=pathlib.Path(sys.argv[2]).resolve(); side=sys.argv[3]
    home=scratch/('claude-'+side); home.mkdir(parents=True,exist_ok=True)
    (home/'settings.json').write_text(json.dumps({'env':{
        'ANTHROPIC_BASE_URL':'http://127.0.0.1:18899',
        'ANTHROPIC_API_KEY':'synthetic-fixture-key',
        'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC':'1'}}))
    settings_file=pathlib.Path('.t3/userdata/settings.json')
    settings=json.loads(settings_file.read_text()) if settings_file.exists() else {}
    settings['providerInstances']={'claudeLimited':{'driver':'claudeAgent','displayName':'Claude Limited',
        'config':{'homePath':str(home),'binaryPath':'/usr/local/bin/claude'}}}
    settings_file.parent.mkdir(parents=True,exist_ok=True)
    settings_file.write_text(json.dumps(settings))
    project=scratch/('project-'+side); project.mkdir(exist_ok=True)
    (project/'README.md').write_text('# Resume demonstration\nSynthetic project for native resume verification.\n')
    subprocess.run(['git','init','-b','main',str(project)],check=True,capture_output=True)
    subprocess.run(['git','-C',str(project),'add','README.md'],check=True)
    subprocess.run(['git','-C',str(project),'-c','user.name=Evidence','-c','user.email=evidence@example.invalid',
        'commit','-m','Initial synthetic project'],capture_output=True)
    result=cli('project','add','--base-dir','.t3','--title','Resume demonstration',str(project))
    if result.returncode: raise RuntimeError(result.stderr)
    result=cli('thread','start','--base-dir','.t3','--provider','claudeLimited','--model','claude-haiku-5-5',
        '--title','Resume once under usage limit','--wait','--json',str(project),
        'Reply with exactly the word PINEAPPLE. Do not use tools.')
    print(result.stdout)
else:
    db=sqlite3.connect('file:.t3/userdata/statev2.sqlite?mode=ro',uri=True)
    db.row_factory=sqlite3.Row
    thread=sys.argv[2]
    print(json.dumps([dict(r) for r in db.execute('select ordinal,status,requested_at,completed_at from orchestration_v2_projection_runs where thread_id=? order by ordinal',(thread,))],indent=2))
