import sys,json,math,os
from cdp import CDP
product,clip,number=sys.argv[1:4]
suffix=sys.argv[4] if len(sys.argv)>4 else ''
questions=["What is the make of each vehicle in this video?","What is the model of each vehicle in this video?","What is the license plate of each vehicle in this video?","List every appearance of each vehicle with timestamps.","What direction of travel is each vehicle going?","List all visible on-screen text in this video.","Who said what in this video, with timestamps?"]
c=CDP(os.environ.get('VS_TARGET') or ('evidencecopilot' if product=='ec' else ('e166ecfa' if clip=='midway' else '332fd292')))
c.call('Page.bringToFront')
selector='[data-testid=chat-panel] [data-status=complete]' if product=='ec' else 'div.rounded-lg.px-3.py-2'
prefix='' if product=='ec' else 'You\n\n'
q=prefix+questions[int(number)-1]
answer_index=os.environ.get('VS_ANSWER_INDEX','i+1')
question_index=os.environ.get('VS_QUESTION_INDEX')
find_question=question_index if question_index else f'a.findLastIndex(e=>e.innerText==={json.dumps(q)})'
start='r' if os.environ.get('VS_ONLY_ANSWER') else 'u'
setup=f'''(()=>{{let a=[...document.querySelectorAll({json.dumps(selector)})];let i={find_question};if(i<0)throw Error("question missing");let u=a[i],r=a[{answer_index}];if(!r)throw Error("answer missing");let s=r.parentElement;while(s&&!["auto","scroll"].includes(getComputedStyle(s).overflowY))s=s.parentElement;if(!s)throw Error("scroller missing");window._vsScroll=s;let t=s.scrollTop+{start}.getBoundingClientRect().top-s.getBoundingClientRect().top-8;let end=s.scrollTop+r.getBoundingClientRect().bottom-s.getBoundingClientRect().top;return {{top:t,end:end,height:s.clientHeight,max:s.scrollHeight-s.clientHeight}}}})()'''
v=c.js(setup)
if not v:raise Exception('Could not locate question and answer')
positions=[max(0,min(v['top'],v['max']))]
while positions[-1]+v['height']<v['end']-2:
    nextpos=min(positions[-1]+v['height']*.82,v['max'])
    if nextpos<=positions[-1]+1:break
    positions.append(nextpos)
for i,p in enumerate(positions):
    c.js(f'window._vsScroll.scrollTop={p}')
    path=f'<local path>{product}_{clip}_q{number}{suffix}'+('' if i==0 else f'_part{i+1}')+'.png'
    c.shot(path)
    print(path)
