"""Create fresh synthetic projects and drive real Pi turns through T3's CLI/RPC.
Initialize a home before starting its dev server; seed one case once the server listens.
"""
import argparse,json,pathlib,subprocess
P=argparse.ArgumentParser();P.add_argument('action',choices=['init','seed','followup']);P.add_argument('--checkout',required=True);P.add_argument('--home',required=True);P.add_argument('--data',required=True);P.add_argument('--case',choices=['primary','steering','command','weak'],default='primary');P.add_argument('--model',default='openai/gpt-6-luna');a=P.parse_args();checkout=pathlib.Path(a.checkout).resolve();home=pathlib.Path(a.home).resolve();data=pathlib.Path(a.data).resolve();extension=pathlib.Path(__file__).with_name('roundtrip.ts').resolve()
def cli(args):
 r=subprocess.run(['node','apps/server/src/bin.ts',*args,'--base-dir',str(home)],cwd=checkout,text=True,capture_output=True);r.check_returncode();return r.stdout
if a.action=='init':
 (home/'userdata').mkdir(parents=True,exist_ok=False);data.mkdir(parents=True,exist_ok=True)
 (home/'userdata/settings.json').write_text(json.dumps({'providerInstances':{'pi':{'driver':'pi','enabled':True,'config':{'launchArgs':f'--no-extensions --no-mcp --no-skills --no-context-files -e {extension} --model {a.model} --thinking off'}}}},indent=2))
else:
 project=data/a.case;result=data/(a.case+'.json')
 if a.action=='seed':
  project.mkdir();(project/'README.md').write_text('Synthetic Pi rewind proof.\n');(project/'.gitignore').write_text('.pi/\n')
  for args in [['init','-q','-b','main',str(project)],['-C',str(project),'add','.'],['-C',str(project),'-c','user.name=Evidence','-c','user.email=evidence@example.invalid','commit','-qm','Initial sample']]:subprocess.run(['git',*args],check=True)
  if a.case=='steering':(project/'.pi').mkdir();(project/'.pi/steering-enabled').touch()
  cli(['project','add','--title','Pi '+a.case,str(project)])
  first=json.loads(cli(['thread','start','--provider','pi','--model','default','--title','Pi '+a.case+' rewind','--wait','--json',str(project),'Reply with exactly the word ONE']));thread=first['threadId'];rows=[first]
  second='/checkpoint' if a.case=='command' else '/weakretain' if a.case=='weak' else 'Reply with exactly the word TWO'
  for message in [second,'/hop','/clonehome','/home']:
   x=json.loads(cli(['thread','send','--wait','--json',thread,message]));rows.append({'message':message,**x})
  output={'threadId':thread,'rows':rows};result.write_text(json.dumps(output,indent=2))
 else:output=json.loads(result.read_text());thread=output['threadId']
 if a.action=='followup' or a.case=='steering':
  message='List, in order, every word I have asked you to reply with so far in this conversation.'
  x=json.loads(cli(['thread','send','--wait','--json',thread,message]));output['rows'].append({'message':message,**x});result.write_text(json.dumps(output,indent=2))
 print(json.dumps(output,indent=2))
