import subprocess,time,sys,pathlib,json
root=pathlib.Path(__file__).parent
side=sys.argv[1]
run=root/('mobile-'+side+'-'+time.strftime('%Y%m%dT%H%M%S'));run.mkdir()
def cmd(*args):
 p=subprocess.run(['agent-device',*args,'--session','auth17114'],text=True,capture_output=True)
 if p.returncode:raise RuntimeError(p.stdout+p.stderr)
 return p.stdout

def stable(label):
 for n in range(12):
  a=run/f'{label}-{n}-a.png';b=run/f'{label}-{n}-b.png'
  cmd('screenshot',str(a));time.sleep(.5);cmd('screenshot',str(b))
  if a.read_bytes()==b.read_bytes():
   (run/f'{label}.png').write_bytes(b.read_bytes());return
 raise RuntimeError('Screen did not settle: '+label)
def navigate(url):
 cmd('fill','role=text-field editable=true',url);cmd('click','label="go"')
cmd('record','start',str(run/'flow.mp4'),'--hide-touches')
try:
 navigate('http://127.0.0.1:18719/public')
 stable('public-start')
 navigate('http://127.0.0.1:18719/auth')
 stable('auth-prompt')
 snapshot=cmd('snapshot','-i');(run/'prompt-accessibility.txt').write_text(snapshot)
 if '"Username"' not in snapshot or 'securetextfield' not in snapshot:
  raise AssertionError('No usable Username/Password prompt; the browser shows the 401 body.')
 cmd('click','label="Dismiss"');stable('cancelled')
 cmd('click','label="Reload page"')
 cmd('snapshot','-i')
 cmd('fill','label="Username" editable=true','tester')
 cmd('fill','label="Password" editable=true','secret')
 stable('credentials-keyboard')
 cmd('click','label="Accept"')
 try:cmd('click','label="Not Now"')
 except RuntimeError:pass
 stable('protected-page')
 print('PASS: native prompt, cancellation, secure password entry, and protected page captured.')
finally:
 cmd('record','stop')
 print(str(run))
