#!/usr/bin/env python3
"""Drive the leased Pixel 9 from the directory that owns its AgentDevice session.
Usage: mobile-driver.py pair before|after
       mobile-driver.py capture before|after S12-overview|S12-index
Navigate Settings > filter > All projects > solo-repo. Capture index, then press Projects for overview.
Clear synthetic app state between sides, reopen the correct Metro bundle, and pair after startup.
Prepare each checkout with `vp run mobile:install android --prepare` before leasing.
Connect proxy and open Pixel 9 with session issue-33607-evidence from /home/ubuntu/t3code.
Install using the pinned checkout's scripts/mobile-native-client.ts from that session directory.
"""
import datetime,json,subprocess,sys,time
from pathlib import Path
from urllib.parse import urlencode
from PIL import Image,ImageChops
ROOT=Path('/tmp/issue-lead-33607-r1/evidence-capture-1')
SESSION='issue-33607-evidence'
SIDE={
 'before':('/home/ubuntu/wt/issue-33607-before',16579,'before-home',18081),
 'after':('/home/ubuntu/wt/issue-33607-evidence-after',15236,'after-pinned-home',18082),
}
action,side=sys.argv[1:3]
checkout,port,home,metro=SIDE[side]
def device(*args):
 return subprocess.run(['agent-device',*args,'--session',SESSION],cwd='/home/ubuntu/t3code',check=True,capture_output=True,text=True).stdout
if action=='pair':
 output=subprocess.run(['node',str(Path(checkout)/'apps/server/src/bin.ts'),'auth','pairing','create','--base-dir',str(ROOT/home),'--base-url','http://<vm-tailnet-host>:18090','--ttl','15m','--label','synthetic-mobile-evidence'],cwd=str(Path(checkout)/'apps/server'),capture_output=True,text=True,check=True).stdout
 url=next(x[len('Pair URL: '):] for x in output.splitlines() if x.startswith('Pair URL: '))
 device('open','com.t3tools.t3code.dev','t3code-dev://connections/new?'+urlencode(dict(pairingUrl=url,autoConnect='1')))
 print('Opened pairing route with a fresh credential; credential not retained.')
elif action=='capture':
 label=sys.argv[3]
 run=ROOT/('mobile-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ'))
 run.mkdir()
 for attempt in range(1,4):
  a=run/f'{label}-{side}-{attempt}-settle-a.png'
  b=run/f'{label}-{side}-{attempt}.png'
  device('screenshot',str(a),'--normalize-status-bar')
  time.sleep(.5)
  device('screenshot',str(b),'--normalize-status-bar')
  if ImageChops.difference(Image.open(a).convert('RGB'),Image.open(b).convert('RGB')).getbbox() is None:
   (run/'manifest.json').write_text(json.dumps(dict(label=label,side=side,path=str(b),stablePixels=0,statusBar='normalized 09:41',theme='dark',fontScale=1,session=SESSION),indent=2)+'\n')
   print(b);break
 else: raise SystemExit('Frames never became pixel-identical; all attempts retained.')
