#!/usr/bin/env python3
from __future__ import annotations
import asyncio, base64, importlib.util, json, mimetypes
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'qa_screenshots'; OUT.mkdir(exist_ok=True)
spec=importlib.util.spec_from_file_location('rc18qa', str(ROOT/'tests/rc18_pose_motion_runtime_safari_scale_real_dom_qa.py'))
rc18qa=importlib.util.module_from_spec(spec); spec.loader.exec_module(rc18qa)

def data_uri(src: str):
    if not src or src.startswith(('data:','http')): return None
    clean=src.split('?',1)[0].split('#',1)[0]
    p=ROOT/clean.lstrip('/')
    if not p.exists() or not p.is_file(): return None
    mime=mimetypes.guess_type(p.name)[0] or 'application/octet-stream'
    return clean, 'data:%s;base64,%s'%(mime,base64.b64encode(p.read_bytes()).decode('ascii'))

async def inline_visible_images(page):
    imgs=await page.evaluate("""() => Array.from(document.querySelectorAll('#exerciseScreen img')).map((img,i)=>({i,src:img.getAttribute('src')||''}))""")
    for im in imgs:
        d=data_uri(im['src'])
        if not d: continue
        clean,uri=d
        await page.evaluate("""({i,uri})=>{const imgs=Array.from(document.querySelectorAll('#exerciseScreen img')); if(imgs[i]) imgs[i].src=uri;}""", {'i':im['i'],'uri':uri})
    await page.wait_for_timeout(80)

async def verify_viewport(playwright,width,height,name):
    browser=await playwright.chromium.launch(executable_path='/usr/bin/chromium', headless=True, args=['--no-sandbox','--disable-dev-shm-usage','--disable-gpu','--disable-gpu-sandbox','--use-gl=swiftshader','--enable-unsafe-swiftshader'])
    page=await browser.new_page(viewport={'width':width,'height':height})
    await page.set_content(rc18qa.inline_preview(), wait_until='domcontentloaded')
    await page.wait_for_function("() => window.startExerciseTestPass && window.openExerciseTestPassOverview && window.showQa && window.currentRows", timeout=10000)
    launcher=await page.evaluate("""() => { window.showQa(); return {visible:!!document.querySelector('.next-library-testpass'), text:document.querySelector('.next-library-testpass')?.textContent.trim()||'', qaInLibrary:Array.from(document.querySelectorAll('.next-library-row')).some(r=>/Övningspass/.test(r.textContent))}; }""")
    if not launcher['visible'] or 'Starta övningspass' not in launcher['text'] or launcher['qaInLibrary']:
        raise AssertionError(f'Launcher/library check failed: {launcher}')
    await page.evaluate("""() => { window.startExerciseTestPass(); window.jumpToStep(1); }""")
    await page.wait_for_timeout(950)
    state=await page.evaluate("""() => ({
      active:document.querySelector('#exerciseScreen')?.classList.contains('active'),
      phase:window.currentRows()[0]?.phase,
      rows:window.currentRows().length,
      qaRows:window.currentRows().filter(r=>r.qaOnly).length,
      name:document.querySelector('#exerciseName')?.textContent.trim()||'',
      hasPose:!!document.querySelector('#videoWrap .has-pose-motion'),
      poseImgs:document.querySelectorAll('#videoWrap img').length,
      media:document.querySelector('[data-media-only]')?.getAttribute('data-media-only') || ''
    })""")
    if not state['active'] or state['phase']!='Övningspass' or state['rows']<10 or state['qaRows']!=state['rows'] or not state['hasPose'] or state['poseImgs']<1:
        raise AssertionError(f'Exercise test pass check failed: {state}')
    await inline_visible_images(page)
    await page.screenshot(path=str(OUT/f'rc24_exercise_test_pass_{name}_{width}x{height}.png'), full_page=False)
    await browser.close()
    return {'launcher':launcher,'state':state}

async def main():
    from playwright.async_api import async_playwright
    results={}
    async with async_playwright() as p:
        for width,height,name in [(390,844,'mobile'),(820,1180,'ipad'),(1440,1024,'desktop')]:
            results[name]=await verify_viewport(p,width,height,name)
    (OUT/'rc24_exercise_test_pass_metrics.json').write_text(json.dumps(results,indent=2,ensure_ascii=False),encoding='utf-8')
    print('RC24 exercise test pass QA OK')

if __name__=='__main__':
    asyncio.run(main())
