"""Record the real mobile removal flow. Run from the session's connected checkout.
Usage: python3 removal-driver.py SESSION OUTPUT_ROOT SIDE
Both runs start with the same thread open, and connections named Primary and Secondary.
"""
import datetime,json,pathlib,subprocess,sys,time
from PIL import Image,ImageChops
session,root,side=sys.argv[1:]
out=pathlib.Path(root)/(side+'-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)
def ad(*args,check=True):
 p=subprocess.run(['agent-device',*args,'--session',session],capture_output=True,text=True)
 (out/'driver.log').open('a').write(' '.join(args)+'\n'+p.stdout+p.stderr+'\n')
 if check and p.returncode: raise RuntimeError(p.stderr)
 return p.stdout

def stable(name):
 for attempt in range(5):
  a=out/(name+'-a.png'); b=out/(name+'.png')
  ad('screenshot',str(a)); time.sleep(.5); ad('screenshot',str(b))
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
   return str(b)
 raise RuntimeError('Screenshots did not stabilize: '+name)

ad('record','start',str(out/'recording.mp4'),'--fps','10','--hide-touches')
try:
 stable('thread-before')
 ad('open','com.t3tools.t3code.dev','t3code-dev://connections')
 stable('two-connections-collapsed')
 ad('press','label="Expand details for Primary"','--settle')
 stable('two-environments')
 ad('press','label="Remove environment"','--settle')
 ad('snapshot','-i')
 ad('press','label="Remove"','--settle')
 # Give the application time to perform any automatic navigation before acting again.
 time.sleep(5)
 sheet=ad('snapshot','-i')
 stable('after-confirmation')
 stayed='"Close environments"' in sheet
 if stayed:
  ad('press','label="Close environments"','--settle')
 time.sleep(2)
 final=ad('snapshot','-i')
 stable('result')
 (out/'observations.json').write_text(json.dumps({'connectionsStayedOpen':stayed,'finalSnapshot':final},indent=2))
finally:
 ad('record','stop',check=False)
print(out)
