import asyncio,json,os,sys
from playwright.async_api import async_playwright
port='8971'
TH={'pearl':('day','white'),'champagne':('day','beige'),'midnight':('night','black'),'amethyst':('night','purple')}
async def main():
  async with async_playwright() as p:
    b=await p.chromium.launch()
    for name,(t,pal) in TH.items():
     for si in '01':
      c=await b.new_context(viewport={'width':390,'height':844},device_scale_factor=2,is_mobile=True,has_touch=True)
      await c.add_init_script(f"try{{localStorage.setItem('wm-theme','{t}');localStorage.setItem('wm-pal','{pal}');localStorage.setItem('wm-pal-day','{pal}');localStorage.setItem('wm-rv','1');localStorage.setItem('wm-si','{si}')}}catch(e){{}}")
      pg=await c.new_page()
      await pg.goto(f'http://localhost:{port}/index.html#aero')
      await pg.wait_for_function("!!(window.WMMERGE&&window.WMTB)",timeout=30000); await pg.wait_for_timeout(1500)
      await pg.evaluate("WMMERGE.show('ato',true)"); await pg.wait_for_timeout(2500)
      fr=[f for f in pg.frames if 'c/app.html' in f.url][0]
      await fr.wait_for_function("!!window.WMAtoPage&&D.atos&&D.atos.length",timeout=20000)
      await fr.evaluate("WMAtoPage.open('SACAA/1115/ATO')"); await pg.wait_for_timeout(1800)
      r=await fr.evaluate("""()=>{const h=document.querySelector('.ap .ap-hero').getBoundingClientRect(),s=document.querySelector('.ap .ap-scroll'),cs=getComputedStyle(document.querySelector('.ap .ap-hero')),sc=getComputedStyle(s);const bodyc=document.querySelector('.ap .ap-body .ap-card');const bc=bodyc&&bodyc.getBoundingClientRect();return {top:h.top,left:h.left,right:innerWidth-h.right,margin:cs.margin,padTop:cs.paddingTop,scrollPadTop:sc.paddingTop,scrollTop:s.getBoundingClientRect().top,bodyCardLeft:bc&&bc.left,vw:innerWidth}}""")
      fe=await pg.evaluate("(()=>{const f=document.getElementById('wmF-c').getBoundingClientRect();return {ftop:f.top}})()")
      r.update(fe); print(name,si,json.dumps(r),flush=True)
      await pg.screenshot(path=f"/workspace/ato_final_v4/{os.environ.get('TAG','x')}_top_{name}_{'in' if si=='1' else 'out'}.png",clip={'x':0,'y':0,'width':390,'height':420})
      await c.close()
    await b.close()
asyncio.run(main())
