import subprocess,sys,time,re,json,hashlib
from pathlib import Path
from PIL import Image, ImageChops
session, parent, side = sys.argv[1:]
out=Path(parent)/(side+'-'+time.strftime('%Y%m%d-%H%M%S'));out.mkdir()
def call(*args):
 p=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 if p.returncode: raise RuntimeError(p.stdout+p.stderr)
 return p.stdout

def row(title):
 tree=call('snapshot','-i')
 match=re.search(r'(@e\d+(?:~s\d+)?) \[cell\] "'+re.escape(title)+r',',tree)
 if not match and title=='Working thread':
  call('press','label="1 working thread"','--settle')
  tree=call('snapshot','-i');match=re.search(r'(@e\d+(?:~s\d+)?) \[cell\] "Working thread,',tree)
 if not match: raise RuntimeError('Missing row '+title+'\n'+tree)
 return match[1]
def capture(label):
 for i in range(3):
  first=out/(label+'-stability-'+str(i)+'.png');last=out/(label+'.png')
  call('screenshot',str(first));time.sleep(.5)
  call('screenshot',str(last))
  if ImageChops.difference(Image.open(first).convert("RGB"),Image.open(last).convert("RGB")).getbbox() is None: return str(last)
 raise RuntimeError('Capture did not stabilize: '+label)
result={}
call('record','start',str(out/'menus.mp4'),'--fps','10')
try:
 for label,title in [('working','Working thread'),('idle','Idle thread - no completed run')]:
  call('longpress',row(title),'--settle')
  call('press','label="More"','--settle')
  tree=call('snapshot','-i')
  if '[button] "Rename"' not in tree: raise RuntimeError('Wrong menu')
  result[label]={'markUnreadVisible':'[button] "Mark unread"' in tree,'capture':capture(label)}
  call('press','30','120','--settle')
finally:
 result['recording']=call('record','stop')
(out/'result.json').write_text(json.dumps(result,indent=2))
print(json.dumps(result,indent=2))
