# Ask one benchmark question in the gamma report Emma chat and capture the rendered answer verbatim.
import sys,json,time,datetime
from cdp import CDP
Q={1:"What is the make of each vehicle in this video?",2:"What is the model of each vehicle in this video?",3:"What is the license plate of each vehicle in this video?",4:"List every appearance of each vehicle with timestamps.",5:"What direction of travel is each vehicle going?",6:"List all visible on-screen text in this video.",7:"Who said what in this video, with timestamps?"}
media,clip,n=sys.argv[1],sys.argv[2],int(sys.argv[3]); q=Q[n]
now=lambda:datetime.datetime.now(datetime.timezone.utc).isoformat()
c=CDP(media); c.call('Page.bringToFront')
MSGS='JSON.stringify([...document.querySelectorAll("div.rounded-lg.px-3.py-2")].map(x=>x.innerText).filter(x=>x.startsWith("You\\n")||x.startsWith("Emma\\n")))'
before=len(json.loads(c.js(MSGS)))
r=c.js('(()=>{let e=document.querySelector("input[placeholder^=\'Ask Emma about this analysis\']");e.scrollIntoView();e.focus();let r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()')
for t in ('mouseMoved','mousePressed','mouseReleased'):
    c.call('Input.dispatchMouseEvent',{'type':t,'x':r['x'],'y':r['y'],'button':'left','clickCount':1})
c.call('Input.insertText',{'text':q})
time.sleep(0.5); c.shot(f'shots_r3/es_{clip}_q{n}_entered.png')
sub=now()
c.call('Input.dispatchKeyEvent',{'type':'keyDown','key':'Enter','code':'Enter','windowsVirtualKeyCode':13,'text':'\r'})
c.call('Input.dispatchKeyEvent',{'type':'keyUp','key':'Enter','code':'Enter','windowsVirtualKeyCode':13})
print('submitted',sub,flush=True)
last=None;stable=0;t0=time.time()
while time.time()-t0<900:
    time.sleep(3)
    m=json.loads(c.js(MSGS))
    new=m[before:]
    busy=c.js('!!document.querySelector("[class*=animate-bounce],[class*=animate-pulse]")')
    if len(new)>=2 and new[0].startswith('You') and new[-1].startswith('Emma') and not busy:
        if new[-1]==last: stable+=1
        else: stable=0; last=new[-1]
        if stable>=3: break
done=now()
ans=last.split('\n',2)[-1].lstrip('\n') if last else None
q_rendered=m[before].split('\n',2)[-1].lstrip('\n')
c.js('(()=>{let m=[...document.querySelectorAll("div.rounded-lg.px-3.py-2")];m[m.length-1].scrollIntoView({block:"start"})})()')
time.sleep(1); c.shot(f'shots_r3/es_{clip}_q{n}.png')
rec={'clip':clip,'question_id':f'Q{n}','question':q,'question_rendered':q_rendered,'submitted_utc':sub,'answer_complete_utc':done,'answer_rendered_text':ans,'messages_after_submit':len(new),'session':c.js(f'localStorage.getItem("emma-report-session-"+location.pathname.split("/")[2])'),'screenshot':f'es_{clip}_q{n}.png'}
open('r3_answers.jsonl','a').write(json.dumps(rec,ensure_ascii=False)+'\n')
print(json.dumps(rec,ensure_ascii=False,indent=1))
