"""Native Android reproduction driver. Run from the checkout owning the pool session.
Setup: a real GitLab MR adds constructor, __proto__, main.ts (one line each),
add its local clone through `t3 project add`, pair the mobile client to a fresh
server, open Pulls > MR, swipe up to expose Changed files, and open __proto__.
Both commits use Pixel 9 / Android 36, 1080x2424, light theme.
Native diff headers do not expose AX nodes; coordinates come from the added-file glyphs in screenshots.
Usage: python reproduction.py before|after SESSION OUTPUT_DIR DATABASE
"""
import sys, subprocess, pathlib, time, sqlite3, json
from PIL import Image
side, session, directory, database = sys.argv[1:]
out=pathlib.Path(directory); out.mkdir(parents=True,exist_ok=False)
def device(*args):
    return subprocess.run(['agent-device',*map(str,args),'--session',session],check=True,capture_output=True,text=True).stdout
def rows():
    with sqlite3.connect(f'file:{database}?mode=ro',uri=True) as db:
        return [r[0] for r in db.execute('select path from pull_request_files_viewed order by path')]
def capture(label):
    a=out/f'{label}.png'; b=out/f'{label}-check.png'
    for attempt in range(5):
        device('screenshot',a); time.sleep(.5); device('screenshot',b)
        if subprocess.run(['compare','-metric','AE',str(a),str(b),'null:'],capture_output=True).returncode==0: break
    else: raise RuntimeError('Screen did not stabilize: '+label)
    states.append({'step':label,'viewedRows':rows()})
def tap_file(index):
    # Added-file glyphs anchor the three native header rows even after collapse.
    shot=out/f'locate-{len(states)}.png'
    device('screenshot',shot)
    im=Image.open(shot).convert('RGB')
    ys=[]
    for y in range(300,1400):
        n=sum(1 for x in range(95,157) if (lambda c:c[0]<65 and 85<c[1]<180 and c[2]<130)(im.getpixel((x,y))))
        if n>=15: ys.append(y)
    groups=[]
    for y in ys:
        if not groups or y-groups[-1][-1]>30: groups.append([y])
        else: groups[-1].append(y)
    if len(groups)!=3: raise RuntimeError(f'Expected three added-file glyphs, got {groups}')
    centers=[(g[0]+g[-1])//2 for g in groups]
    device('press',1027,centers[index])
states=[]
device('record','start',out/'interaction.mp4')
capture('initial-diff')
tap_file(1)
capture('first-constructor')
tap_file(2)
capture('main-control')
tap_file(1)
capture('second-constructor')
tap_file(0)
capture('first-proto')
device('press','label="Navigate up"','--settle')
capture('final-list')
device('record','stop')
(out/'viewed-rows.json').write_text(json.dumps(states,indent=2)+'\n')
print(json.dumps(states,indent=2))
