#!/usr/bin/env python3
"""Real-app title proof. Start each commit with T3CODE_DEV_SEED=0 vp run dev.
Usage: AGENT_BROWSER_BIN=agent-browser python3 capture.py WORKTREE ORIGIN PAIR_URL SESSION OUTPUT STAGE [VARIANT START COUNT]
The worktree must have dependencies installed. Uses fresh synthetic project data only.
"""
import os, sys, subprocess, json, time, re, sqlite3, pathlib, hashlib, datetime
wt,origin,pair,session,out,stage,*rest=sys.argv[1:]
out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
ab=os.environ.get('AGENT_BROWSER_BIN','agent-browser')
def run(*args):
 print('ACTION',args[0],str(args[1:])[:180] if args[0]!='open' else '(navigate)',flush=True)
 p=subprocess.run([ab,'--session',session,*args],text=True,capture_output=True,env={**os.environ,'AGENT_BROWSER_DEFAULT_TIMEOUT':'90000'})
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout.strip()
def ev(js):
 s=run('eval',js)
 try:return json.loads(s)
 except:return s
def click(role,name):return run('find','role',role,'click','--name',name)
def wait(text):
 if text=='Submit message':return run('wait','--fn',"!!document.querySelector('[aria-label=\"Submit message\"]')")
 return run('wait','--text',text)
def snapshot():return run('snapshot','-i')
def shot(name):
 ev('document.activeElement?.blur()')
 prev=None
 for n in range(16):
  path=out/(name+('.png' if n%2 else '-stable.png'))
  run('screenshot',str(path))
  data=path.read_bytes()
  if data==prev:
   if path.name!=name+'.png': (out/(name+'.png')).write_bytes(data)
   return
  prev=data;time.sleep(.5)
 raise RuntimeError('Unstable screenshot: '+name)
def dbthread(tid):
 with sqlite3.connect(f'file:{wt}/.t3/userdata/statev2.sqlite?mode=ro',uri=True) as db:
  row=db.execute('select payload_json from orchestration_v2_projection_threads where thread_id=?',(tid,)).fetchone()
  return json.loads(row[0]) if row else None
def settled(tid):
 end=time.monotonic()+210
 saw=False
 while time.monotonic()<end:
  row=dbthread(tid)
  if row and not row.get('titleRegeneration') and row.get('titleState',{}).get('type')!='generating' and row['title']!='New thread':
   return row
  time.sleep(.5)
 raise RuntimeError('Title did not finish')

if stage=='setup':
 
 if pair != '-':
  run('open',pair)
  run('wait','--fn',"!!document.querySelector('[aria-label=\"Pairing token\"]') || !!document.querySelector('[aria-label^=\"Message \"]')")
  if 'textbox \"Pairing token\"' in snapshot():
   run('find','role','textbox','fill','--name','Pairing token',pair.split('token=')[1]);click('button','Continue')
 run('wait','--fn',"!!document.querySelector('[aria-label^=\"Message \"]') || !!document.querySelector('[aria-label=\"Search settings\"]')")
 run('set','viewport','1920','1080')
 run('open',origin+'/settings/threads');wait('Text generation model')
 # Default chat uses recorded output; title generation remains the real Codex Luna model.
 
 if 'button \"GPT-6-Astra\"' in snapshot():
  click('button','GPT-6-Astra');click('button','Replay (dev)');click('option','Showcase , Replay (dev) Add to favorites')
 # Create the same synthetic project on both commits.
 project=out.parent/'fixture';project.mkdir(exist_ok=True)
 p=subprocess.run(['node','apps/server/src/bin.ts','project','add','--base-dir','.t3','--title','Title proof',str(project)],cwd=wt,text=True,capture_output=True)
 print('Synthetic project ready',flush=True)
 # Open the initial blank thread, collapse details before recording to keep local workspace details private.
 click('button','Close');wait('Submit message')
 s=snapshot()
 if 'region "Thread details"' in s: click('button','Toggle thread details panel')
 sys.exit(0)

variants=[
 ('expanded','Title every thread "Owner: what it does (model effort)". The owner is Julius, the model is GPT-6 Astra and the effort is medium. Describe what it does in full, in lowercase.',5),
 ('literal','Title every thread "Owner: what it does (model effort)".',5),
 ('exact','Use exactly this title, word for word: "Owner: relay chat messages to the lead agent (model effort)"',5),
 ('boundary','Use exactly this title, word for word: "Owner: relay chat messages from the team channel to the lead agent while all subagents keep working (GPT-6 Astra medium)"',2),
 ('over-limit','Use exactly this title, word for word: "Owner: relay chat messages from the team channel to the lead agent so it can answer every incoming question while all subagents continue working independently (GPT-6 Astra medium)"',2)]
msg='Relay chat messages from the team channel to the lead agent so it can answer them while subagents keep working.'
results=json.loads((out/'results.json').read_text()) if (out/'results.json').exists() else []
selected,start,count=rest[0],int(rest[1]),int(rest[2])
for label,instructions,_ in variants:
 if label!=selected:continue
 run('open',origin+'/settings/threads');wait('Text generation model')
 if 'button \"Advanced\" [expanded=false' in snapshot():click('button','Advanced')
 time.sleep(.5)
 run('find','role','textbox','fill','--name','Thread title instructions',instructions)
 ev('document.activeElement?.blur()')
 # Scroll enough to show both title model and saved instructions.
 time.sleep(.5)
 ev('(()=>{const e=document.querySelector(\'[aria-label="Thread title instructions"]\');for(let p=e.parentElement;p;p=p.parentElement){const o=getComputedStyle(p).overflowY;if(o==="hidden")p.scrollTop=0;if(o==="auto")p.scrollTop=p.scrollHeight;}})()')
 ev('document.activeElement?.blur()')
 run('wait','--fn',"!!document.querySelector('[aria-label=\"Thread title instructions\"]') && location.pathname.includes('/settings/')")
 shot(label+'-settings')
 videoName=f'{label}-{start}-{start+count-1}-{stage}-{time.time_ns()}.mp4'
 click('button','Close');wait('Submit message')
 if 'region \"Thread details\"' in snapshot():click('button','Toggle thread details panel')
 if os.environ.get('REGEN_ONLY')!='1':run('record','start',str(out/videoName),'--fps','5')
 for trial in range(start,start+count):
  if stage!='case' and len(rest)>3:
   env=ev('fetch(\'/.well-known/t3/environment\').then(r=>r.json()).then(r=>r.environmentId)')
   run('open',origin+'/'+env+'/'+rest[3]);run('wait','--fn',"!!document.querySelector('[aria-label^=\"Thread actions for\"]')")
  if stage=='case':
   click('button','New thread in')
   wait('Submit message')
   run('find','role','textbox','fill','--name','Message New thread',msg)
   with sqlite3.connect(f'file:{wt}/.t3/userdata/statev2.sqlite?mode=ro',uri=True) as db:
    existing={x[0] for x in db.execute('select thread_id from orchestration_v2_projection_threads')}
   click('button','Submit message')
   end=time.monotonic()+60
   while time.monotonic()<end:
    with sqlite3.connect(f'file:{wt}/.t3/userdata/statev2.sqlite?mode=ro',uri=True) as db:
     created=[x[0] for x in db.execute('select thread_id from orchestration_v2_projection_threads') if x[0] not in existing]
    if created:break
    time.sleep(.5)
   else:raise RuntimeError('New thread was not created')
   assert len(created)==1
   env=ev('fetch(\'/.well-known/t3/environment\').then(r=>r.json()).then(r=>r.environmentId)')
   run('open',origin+'/'+env+'/'+created[0]);run('wait','--fn',"!!document.querySelector('[aria-label^=\"Thread actions for\"]')")
  url=run('get','url')
  import urllib.parse
  tid=urllib.parse.unquote(urllib.parse.urlparse(url).path.split('/')[-1])
  (out/'pending.json').write_text(json.dumps({'variant':label,'trial':trial,'threadId':tid}))
  initial=settled(tid)
  # The title operation finishes before the replayed response; await the replay completion too.
  run('wait','--fn',"!document.querySelector('[aria-label=\"Stop response\"]') && !!document.querySelector('[aria-label=\"Submit message\"]')")
  run('wait','--fn',"document.querySelector('[aria-label^=\"Thread actions for\"]')?.getAttribute('aria-label').slice(19) === "+json.dumps(initial['title']))
  if stage!='finish':shot(f'{label}-{trial}-initial')
  if os.environ.get('REGEN_ONLY')=='1':
   if 'region \"Thread details\"' in snapshot():click('button','Toggle thread details panel')
   run('record','start',str(out/videoName),'--fps','10')
   time.sleep(2)
  item={'variant':label,'trial':trial,'instructions':instructions,'initial':rest[4] if stage=='finish' else initial['title'],'initialChars':len(rest[4] if stage=='finish' else initial['title'])}
  row=initial
  if stage!='finish':
   # Capture the same scripted menu interaction for every regeneration.
   click('button','Thread actions for')
   time.sleep(1.5)
   click('menuitem','Regenerate title')
   # Wait for the operation's lifecycle, including unchanged returned titles.
   time.sleep(.3)
   end=time.monotonic()+210
   previous=(initial.get('lastTitleRegeneration') or {}).get('requestId')
   while time.monotonic()<end:
    row=dbthread(tid)
    if row and not row.get('titleRegeneration') and (row.get('lastTitleRegeneration') or {}).get('requestId') not in (None,previous):break
    time.sleep(.5)
   else:raise RuntimeError('Regeneration did not finish')
  run('wait','--fn',"document.querySelector('[aria-label^=\"Thread actions for\"]')?.getAttribute('aria-label').slice(19) === "+json.dumps(row['title']))
  item.update(regenerated=row['title'],regeneratedChars=len(row['title']),regenerationStatus=row.get('lastTitleRegeneration',{}).get('status'),videoFile=videoName)
  results=[x for x in results if (x['variant'],x['trial'])!=(label,trial)]
  results.append(item);(out/'results.json').write_text(json.dumps(results,indent=2))
  print(json.dumps(item),flush=True)
  shot(f'{label}-{trial}-regenerated')
 time.sleep(2)
 run('record','stop')
print('OUTPUT',out,flush=True)
