"""Real-app evidence driver. No application source or capability responses are changed.
Usage: python driver.py AGENT_BROWSER SESSION ARTIFACT_ROOT setup|capture [options]
setup opens the synthetic project from the existing authenticated app.
capture records the same right-click and activates Reveal only when it exists.
For capture pass SIDE DISPLAY XAUTHORITY. Original server paths are masked in video.
"""
import subprocess,sys,time,pathlib,re,json,os,datetime,signal
browser,session,root,mode,*args=sys.argv[1:]
out=pathlib.Path(root)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
out.mkdir(parents=True)
def ab(*argv):
 p=subprocess.run([browser,'--session',session,*argv],capture_output=True,text=True)
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout

def click(role,name): return ab('find','role',role,'click','--name',name)
if mode=='setup':
 ab('set','viewport','1280','800')
 click('button','New thread')
 snapshot=ab('snapshot','-i')
 ref=re.search(r'option "File menu demo[^\n]*\[ref=(e\d+)\]',snapshot).group(1)
 ab('click','@'+ref);ab('press','Enter')
 click('button','Toggle right panel');click('button','Files F')

 for attempt in range(20):
  if 'treeitem "hello.ts"' in ab('snapshot','-i'):break
  time.sleep(.5)
 else:raise RuntimeError('Synthetic file did not appear')
 click('button','Maximize panel');click('button','Toggle main sidebar')
 print(out)
elif mode=='capture':
 side,display,authority=args
 env={**os.environ,'DISPLAY':display,'XAUTHORITY':authority}
 origin=ab('get','url').strip().split('/')[0:3]
 (out/'environment.json').write_text(json.dumps({'side':side,'surface':'web','originKind':'HTTPS non-loopback address' if 'https:' in origin else 'HTTP localhost','viewport':[1280,800],'theme':'light','sample':'hello.ts'},indent=2))
 ab('press','Escape')
 log=open(out/'server-recording.log','w')
 recording=subprocess.Popen(['ffmpeg','-y','-f','x11grab','-framerate','15','-video_size','890x550','-i',display+'+0,0','-vf','drawbox=x=280:y=0:w=370:h=55:color=black:t=fill','-c:v','libx264','-preset','ultrafast','-pix_fmt','yuv420p',str(out/'server.mp4')],env=env,stdout=log,stderr=log)
 try:
  ab('record','start',str(out/'browser.mp4'),'--cursor')
  time.sleep(1)
  ab('mouse','move',*(['75','108'] if 'diff' in side else ['180','104']));ab('mouse','down','right');ab('mouse','up','right')
  menu=ab('snapshot','-i')
  entries=re.findall(r'menuitem "([^"]+)"',menu)
  (out/'menu.json').write_text(json.dumps(entries,indent=2))
  for attempt in range(12):
   ab('screenshot',str(out/'menu-a.png'));time.sleep(.5);ab('screenshot',str(out/'menu.png'))
   if (out/'menu-a.png').read_bytes()==(out/'menu.png').read_bytes():break
  else:raise RuntimeError('Menu did not become visually stable')
  time.sleep(2)
  if 'Reveal in Files' in entries:click('menuitem','Reveal in Files')
  time.sleep(4)
  ab('record','stop')
 finally:
  recording.send_signal(signal.SIGINT);recording.wait();log.close()
 print(out)
