import json, subprocess, sys, urllib.request, pathlib, time
from PIL import Image
side, port, output = sys.argv[1:]
root=pathlib.Path(output) / (side+'-'+time.strftime('%Y%m%d-%H%M%S'))
root.mkdir()
def call(*args):
    result=subprocess.run(['agent-device',*args,'--session','cr-fence-proof'],check=True,capture_output=True)
    return result.stdout.decode()
with urllib.request.urlopen(f'http://127.0.0.1:{port}/.well-known/t3/environment') as response:
    env=json.load(response)['environmentId']
inside=f'<t3-thread://v2/{env}/inside-fence>'
after=f'<t3-thread://v2/{env}/after>'
results=[]
print(call('record','start',str(root/'paste.mp4'),'--hide-touches'),flush=True)
for label,text in [('cr-only',f'~~~\r{inside}\r~~~'),('lf-control',f'~~~\n{inside}\n~~~'),('cr-after-fence',f'```\r{inside}\r```\r{after}')]:
    call('fill','label="Ask anything" editable=true','')
    call('clipboard','write',text)
    read=json.loads(call('clipboard','read','--json'))['data']['text']
    assert read==text,repr(read)
    call('longpress','label="Ask anything" editable=true','800')
    call('tap','role=text label="Paste"')
    snapshot=call('snapshot','-i')
    call('tap','200','310')
    stable=False
    previous=None
    for i in range(8):
        path=root/f'{label}-{i}.png'
        call('screenshot',str(path))
        current=Image.open(path).tobytes()
        if current==previous:
            (root/f'{label}.png').write_bytes(path.read_bytes())
            stable=True
            break
        previous=current
        time.sleep(.5)
    results.append({'label':label,'clipboardPreserved':read==text,'stable':stable,'snapshot':snapshot})
    print(label,snapshot,flush=True)
print(call('record','stop'),flush=True)
(root/'observations.json').write_text(json.dumps(results,indent=2))
print(root,flush=True)
