import pathlib, subprocess, sys, time, shutil
from PIL import Image, ImageChops
session, output = sys.argv[1:3]
out=pathlib.Path(output);out.mkdir(parents=True,exist_ok=True)
log=open(out/'driver-local.log','w')
def run(*args,check=True):
 p=subprocess.run(['agent-device',*args,'--session',session],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 log.write(p.stdout);log.flush()
 if check and p.returncode: raise RuntimeError('Device command failed: '+args[0])
 return p

def capture(label):
 previous=out/(label+'-stable-0.png');run('screenshot',str(previous))
 for i in range(1,17):
  time.sleep(.5 + ((i-1) % 4) * .15)
  current=out/(label+f'-stable-{i}.png');run('screenshot',str(current))
  if ImageChops.difference(Image.open(previous).convert('RGB'),Image.open(current).convert('RGB')).getbbox() is None:
   shutil.copyfile(current,out/(label+'.png'));return
  previous=current
 raise RuntimeError('The capture did not stabilize: '+label)
run('record','start',str(out/'interaction.mp4'),'--hide-touches')
try:
 run('fill','role=text-view','#Café','--settle')
 run('wait','text','Größe Café')
 capture('001-title-nfc')
 run('fill','role=text-view','#Cafe\u0301','--settle')
 # Both sides get the same bounded wait. Base is expected to have lost this result.
 run('wait','text','Größe Café',check=False)
 (out/'nfd-screen.txt').write_text(run('snapshot','-i').stdout)
 capture('002-title-nfd')
finally:
 run('record','stop',check=False)
log.close()
print('Captured NFC and NFD title searches.')
