#!/usr/bin/env python3
"""Run from either installed checkout: python3 reproduce.py <output-parent> <free-port>."""
import datetime,json,pathlib,sqlite3,subprocess,sys,time
root=pathlib.Path(sys.argv[1]).resolve()/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ'); root.mkdir(parents=True)
data=root/'data'; (data/'userdata').mkdir(parents=True)
favorites=['openai/gpt-5.4-mini','anthropic/claude-haiku-4-5','openai/gpt-5.2']
(data/'userdata/settings.json').write_text(json.dumps({'providerInstances':{'opencode':{'driver':'opencode','enabled':True}},'favorites':[{'provider':'opencode','model':m} for m in favorites]}))
project=root/'project'; project.mkdir(); subprocess.run(['git','init',str(project)],check=True,capture_output=True)
cli=['node','apps/server/src/bin.ts']; import os
env=dict(os.environ,T3CODE_DEV_SEED='0')
with (root/'server.log').open('w') as log:
 server=subprocess.Popen(cli+['serve','--base-dir',str(data),'--host','127.0.0.1','--port',sys.argv[2]],env=env,stdout=log,stderr=log)
 try:
  import urllib.request
  for attempt in range(120):
   try: urllib.request.urlopen('http://127.0.0.1:'+sys.argv[2]+'/health'); break
   except Exception: time.sleep(.5)
  subprocess.run(cli+['project','add','--base-dir',str(data),'--title','Favorite model proof',str(project)],check=True,capture_output=True)
  reply=subprocess.run(cli+['thread','start','--base-dir',str(data),'--provider','opencode','--model','xai/grok-4.6','--wait','--json',str(project),'Call orchestrator_capabilities exactly once with no arguments, list the opencode model ids and say which are my favorites according to that response alone'],check=True,capture_output=True,text=True)
  (root/'reply.json').write_text(reply.stdout)
  c=sqlite3.connect(f'file:{data}/userdata/statev2.sqlite?mode=ro',uri=True)
  items=[json.loads(r[0]) for r in c.execute('select payload_json from orchestration_v2_projection_turn_items order by ordinal')]
  calls=[v for v in items if v['type']=='dynamic_tool' and 'orchestrator_capabilities({})' in json.dumps(v.get('input'))]
  provider=[v for v in json.loads(calls[0]['output'])['providers'] if v['providerInstanceId']=='opencode'][0]
  (root/'capture.json').write_text(json.dumps({'capabilityCalls':len(calls),'opencodeResponse':provider,'agentAnswer':json.loads(reply.stdout)['reply']},indent=2)+'\n')
  print(root/'capture.json')
 finally:
  server.terminate(); server.wait(timeout=30)
