#!/usr/bin/env python3
"""Run with DISPLAY/XAUTHORITY set; argument is a new output directory.
Requires the desktop browser maximized inside a 1440x900 window at (0,0),
sidebar width 256, and the supplied page loaded. Uses XTest OS input, no CDP.
"""
import os, pathlib, subprocess, sys, time
out = pathlib.Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=False)
def x(*args): subprocess.run(['xdotool', *args], check=True)
def click(a,b):
    x('mousemove',str(a),str(b)); time.sleep(.3); x('click','1'); time.sleep(1)
def screenshot(name):
    a=out/(name+'-a.png'); b=out/(name+'.png')
    for p in (a,b):
        subprocess.run(['import','-window','root','-crop','1184x900+256+0','+repage',str(p)],check=True)
        time.sleep(.5)
    result=subprocess.run(['compare','-metric','AE',str(a),str(b),'null:'],capture_output=True,text=True)
    print(name, 'stable pixel difference:',result.stderr,flush=True)
# Reload through host toolbar; do not click the guest before the first case.
x('key','Escape'); time.sleep(.5); click(328,54); time.sleep(2)
rec=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-draw_mouse','1','-framerate','15','-video_size','1184x900','-i',os.environ['DISPLAY']+'+256,0','-c:v','libx264','-preset','ultrafast','-crf','22','-pix_fmt','yuv420p',str(out/'interaction.mp4')],stdin=subprocess.PIPE)
try:
    time.sleep(1)
    for n in (1,2):
        click(1420,54); screenshot('menu-'+str(n))
        click(440,335); screenshot('click-'+str(n)); time.sleep(1); x('key','Escape'); time.sleep(.5)
    # Give the menu trigger keyboard focus, then open it using Space.
    click(1420,54); x('key','Escape'); time.sleep(1); x('key','space'); time.sleep(1)
    screenshot('keyboard-menu'); click(440,335); screenshot('keyboard-click'); time.sleep(2)
finally:
    rec.communicate(b'q\n',timeout=15)
