"""Drive the real iOS composer through native clipboard Paste on either checkout.
Usage: python3 paste-cases.py SESSION OUTPUT_PARENT SIDE
Start a fresh server, seed one replay thread, pair the client and open that thread first.
"""
import datetime, json, pathlib, subprocess, sys, time
from PIL import Image, ImageChops
session, parent, side = sys.argv[1:]
out = pathlib.Path(parent) / (side + '-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
out.mkdir(parents=True)
log = (out / 'commands.log').open('w')
def cmd(*args, as_json=False):
    invocation = ['agent-device', *args, '--session', session]
    if as_json: invocation.append('--json')
    r = subprocess.run(invocation, capture_output=True, text=True)
    log.write(json.dumps(list(args)) + '\n' + r.stdout + r.stderr + '\n'); log.flush()
    if r.returncode: raise RuntimeError('Device command failed: ' + ' '.join(args[:2]))
    return json.loads(r.stdout)['data'] if as_json else r.stdout
cases = [
 ('01-CR-closed', '```math\r@note \r```'),
 ('02-LF-closed', '```math\n@note \n```'),
 ('03-CRLF-closed', '```math\r\n@note \r\n```'),
 ('04-CR-unclosed', '```math\r@note '),
 ('05-CR-shorter-closer', '````math\r@note \r```'),
 ('06-CR-mismatched-closer', '```math\r@note \r~~~'),
 ('07-CR-blockquote', '> ```math\r> @note \r> ```'),
 ('08-CR-indented-closer', '```math\r@note \r    ```'),
 ('09-LF-indented-closer', '```math\n@note \n    ```'),
]
results=[]
cmd('record', 'start', str(out / 'paste-sequence.mp4'), '--fps', '10', '--hide-touches')
try:
  for label, payload in cases:
    cmd('fill', 'role=text-view', '', '--settle')
    cmd('clipboard', 'write', payload)
    readback=cmd('clipboard', 'read', as_json=True)['text']
    if readback != payload:
      results.append({'label':label,'payload':payload,'clipboardExact':False,'readback':readback,'skipped':'Clipboard normalized line endings; not evidence for this case'})
      print(label, 'SKIPPED: clipboard normalized line endings', flush=True)
      continue
    cmd('longpress', 'label="Ask anything" editable=true', '1000', '--settle')
    cmd('press', 'role=menu-item label="Paste"', '--settle')
    snapshot=cmd('snapshot', '-i')
    (out / (label + '-snapshot.txt')).write_text(snapshot)
    chip='[button] "note"' in snapshot
    stable=False
    for attempt in range(6):
      a=out / (label + '-check.png'); b=out / (label + '.png')
      cmd('screenshot', str(a)); time.sleep(.5); cmd('screenshot', str(b))
      stable=ImageChops.difference(Image.open(a).convert('RGB'), Image.open(b).convert('RGB')).getbbox() is None
      if stable: break
    results.append({'label':label,'payload':payload,'clipboardExact':True,'mentionChip':chip,'stablePair':stable,'capture':str(b)})
    (out/'observations.json').write_text(json.dumps(results,indent=2))
    print(label, 'CHIP' if chip else 'literal', 'stable='+str(stable), flush=True)
finally:
  cmd('record', 'stop')
  print('Output:',out,flush=True)
