#!/usr/bin/env python3
import sys,time,json,os
from pathlib import Path
from datetime import datetime,timezone
from capture import ab,js,settled,ROOT,HOST,PORT
side=sys.argv[1]
rows=sys.argv[2:] or ['M','F','C','T','G','A','D','I','O','Z','W']
run=ROOT/datetime.now(timezone.utc).strftime('harness-%Y%m%dT%H%M%SZ')
run.mkdir()
print(run,flush=True)
for width,theme in [(1440,'dark'),(1440,'light'),(390,'dark'),(390,'light')]:
    if os.getenv('EVIDENCE_VIEWPORT') and os.getenv('EVIDENCE_VIEWPORT') != f'{width}-{theme}':
        continue
    height=900 if width==1440 else 844
    ab('set','viewport',width,height,1);ab('set','media',theme,'reduced-motion')
    ab('open',f'http://{HOST[side]}:{PORT[side]}/welcome')
    ab('wait','--text','Connect your computers')
    js((ROOT/'harness.js').read_text());js((ROOT/'fixtures.js').read_text())
    for row in rows:
        folder=run/f'{side}-{row}-{width}-{theme}';folder.mkdir()
        try:
            config=js('window.harness.configure('+json.dumps(row)+')')
            if row=='W' and os.getenv('EVIDENCE_W_EMPTY')=='1':
                js("window.harness.sceneReset([window.harness.S(window.harness.A,[])]);window.harness.steps[2]={label:'Show populated result at 20px system font',action:()=>window.harness.sceneReset([window.harness.S(window.harness.A,[window.harness.candidate('demo-pi-app')])])}")
                config=js("({row:'W',steps:window.harness.steps.map(s=>s.label)})")
            ab('wait','--text','Import your projects')
            if row=='G':
                ab('find','role','button','click','--name','Select none','--exact')
            settled(folder/'initial.png')
            environment=js("({browser:navigator.userAgent,deviceEmulation:false,dpr:devicePixelRatio,fontScaling:getComputedStyle(document.documentElement).fontSize,viewport:[innerWidth,innerHeight],reducedMotion:matchMedia('(prefers-reduced-motion: reduce)').matches,theme:matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light',clock:new Date().toISOString(),harness:true})")
            (folder/'environment.json').write_text(json.dumps(environment,indent=2))
            (folder/'steps.json').write_text(json.dumps(config,indent=2))
            if config['steps']:
                ab('record','start',folder/'interaction.webm','--fps','30')
                timeline=[];start=time.monotonic()
                try:
                    for i,label in enumerate(config['steps']):
                        time.sleep(1.5)
                        result=js(f'window.harness.steps[{i}].action()')
                        if label.startswith('Hover and focus'):
                            ab('find','first','label [data-slot=tooltip-trigger]','hover')
                            ab('focus','label [data-slot=tooltip-trigger] >> nth=0')
                            time.sleep(1)
                            (folder/'tooltip-observation.json').write_text(json.dumps(js("({active:{tag:document.activeElement.tagName,slot:document.activeElement.getAttribute('data-slot'),tabIndex:document.activeElement.tabIndex},tooltips:[...document.querySelectorAll('[role=tooltip]')].map(e=>e.textContent)})"),indent=2))
                        if label.startswith('Fresh scene: outside click'):
                            time.sleep(.2);ab('mouse','move',0,0);ab('mouse','down','left');ab('mouse','up','left')
                        if label=='Fresh scene then Escape':
                            time.sleep(.2);ab('press','Escape')
                        if label=='Attempt Back and Close while importing':
                            ab('press','Escape')

                        if isinstance(result,dict) and 'viewport' in result:
                            target=width if result['viewport']=='restore' else result['viewport']
                            ab('set','viewport',target,height,1)
                        timeline.append({'seconds':round(time.monotonic()-start,3),'action':label})
                    time.sleep(2)
                finally:
                    ab('record','stop')
                (folder/'timeline.json').write_text(json.dumps(timeline,indent=2))
            (folder/'result.json').write_text(json.dumps(js("({body:document.body.innerText,done:window.harness.done,viewport:[innerWidth,innerHeight]})"),indent=2))
            print('captured',side,row,width,theme,flush=True)
        except Exception as e:
            (folder/'failure.private.txt').write_text(str(e));print('FAILED',side,row,width,theme,str(e)[:300],flush=True)
