# Before each question: back up and clear the org+media Emma thread (gamma only), reload the report, History -> New chat, confirm empty.
import sys,json,time,boto3,subprocess
from cdp import CDP
REP={'midway':('e166ecfa-ba7d-43ae-b600-0cc4b97705b3','media-146ca20f3e16889b9251ee432964515bafe4aee2'),
     'nasa':('80e168fc-73d6-4c33-9b57-b576117f99f8','media-b4dcbb75f9b8d9eda83c66f11a754910c9e4d5e8')}
clip,n=sys.argv[1],sys.argv[2]; mid,sid=REP[clip]
t=boto3.resource('dynamodb',region_name='us-east-1').Table('gamma-echosaw-chat-conversations')
q=lambda: t.query(KeyConditionExpression=boto3.dynamodb.conditions.Key('sessionId').eq(sid))['Items']
items=q(); json.dump(items,open(f'r3/thread_before_q{n}.json','w'),default=str,indent=1)
for i in items: t.delete_item(Key={'sessionId':sid,'turnId':i['turnId']})
print('deleted',len(items),'remaining',len(q()))
c=CDP('app.gamma.echosaw.com/report/')
c.call('Page.navigate',{'url':f'https://app.gamma.echosaw.com/report/{mid}/'}); time.sleep(14)
for txt in ('History','New chat'):
    print(subprocess.run(['python3','clicktext.py',mid,txt],capture_output=True,text=True).stdout.strip()); time.sleep(2)
c.shot(f'shots_r3/{clip}_q{n}_new_chat.png')
msgs=c.js('[...document.querySelectorAll("div.rounded-lg.px-3.py-2")].filter(x=>x.innerText.startsWith("You\\n")||x.innerText.startsWith("Emma\\n")).length')
print('panel messages',msgs,'thread rows',len(q()))
