import argparse, json, subprocess, time
from pathlib import Path
p=argparse.ArgumentParser()
p.add_argument('phase', choices=['copy','paste','repeat','inspect','gallery'])
p.add_argument('--session', required=True)
p.add_argument('--out', required=True)
a=p.parse_args()
out=Path(a.out); out.mkdir(parents=True,exist_ok=True)
def call(*args):
    r=subprocess.run(['agent-device',*args,'--session',a.session,'--json'],capture_output=True,text=True)
    (out/'actions.log').open('a').write(f'{time.time():.3f} {args!r}\n{r.stdout}\n{r.stderr}\n')
    if r.returncode: raise RuntimeError(f'{args[0]} failed: {r.stderr}')
    return json.loads(r.stdout).get('data',{})
def nodes(): return call('snapshot','-i')['nodes']
def tap(label, kind=None):
    ns=nodes(); hits=[n for n in ns if n.get('label')==label and (not kind or n.get('kind')==kind)]
    if not hits: raise RuntimeError(f'No {label}: '+str([(n.get('kind'),n.get('label')) for n in ns]))
    call('press','@'+hits[0]['ref'])
def shot(name): call('screenshot',str(out/(name+'.png')))
if a.phase=='copy':
    ns=nodes()
    if any(n.get('label')=='Continue' for n in ns):
        tap('Continue','button')
        call('alert','dismiss')
    tap('Select','button')
    for i in range(5):
        photos=[n for n in nodes() if n.get('kind')=='image' and n.get('label','').startswith('Photo')]
        call('press','@'+photos[i]['ref'])
    tap('Share','button')
    tap('Copy Photos','text')
    call('open','com.t3tools.t3code.dev')
elif a.phase in ['paste','repeat']:
    ns=nodes(); editor=next(n for n in ns if n.get('kind')=='text-view')
    if a.phase=='repeat':
        r=editor['rect']; x=str(round(r['x']+r['width']-10)); y=str(round(r['y']+r['height']-10))
        call('press',x,y)
        call('longpress',x,y)
    else:
        call('press','@'+editor['ref'])
        ns=nodes(); editor=next(n for n in ns if n.get('kind')=='text-view')
        call('longpress','@'+editor['ref'])
    shot('paste-menu')
    call('record','start',str(out/'paste.mp4'),'--hide-touches')
    started=time.monotonic()
    tap('Paste','menu-item')
    ns=nodes()
    if any(n.get('label')=='Allow Paste' for n in ns): tap('Allow Paste','button')
    shot('after-paste')
    call('wait','7000')
    shot('after-7-seconds')
    call('wait','25000')
    shot('after-preparation')
    call('record','stop')
    (out/'elapsed.txt').write_text(str(time.monotonic()-started))
    print([(n.get('kind'),n.get('label')) for n in nodes()])
elif a.phase=='gallery':
    ns=nodes(); image=[n for n in ns if n.get('kind')=='button' and n.get('label','').startswith('Open pasted-image.')][-1]
    call('press','@'+image['ref'])
    call('wait','stable','500','10000')
    shot('stable-a'); call('wait','500'); shot('stable-b')
    from PIL import Image, ImageChops
    if ImageChops.difference(Image.open(out/'stable-a.png'),Image.open(out/'stable-b.png')).getbbox() is not None: raise RuntimeError('Gallery did not hold still')
    shot('gallery')
    print([(n.get('kind'),n.get('label')) for n in nodes()])
else:
    print([(n.get('kind'),n.get('label')) for n in nodes()])
