# Controleert horizontale overflow op 360-430px met Playwright.
# Gebruik: python scripts/mobile-overflow.py https://git.timfalken.com UIT /pad1 /pad2 ...
# UIT = map voor screenshots; "voor" gebruikt de live CSS, anders de lokale style.css.
import sys
from playwright.sync_api import sync_playwright
css=open(__import__('os').path.join(__import__('os').path.dirname(__file__),'..','internal','server','static','style.css')).read()
base,out=sys.argv[1],sys.argv[2]; pages=sys.argv[3:]
JS="""(w)=>{const out=[];for(const e of document.querySelectorAll('body *')){const r=e.getBoundingClientRect();if(r.right<=w+1||r.width==0)continue;let a=e.parentElement,clip=false;while(a&&a!==document.body&&a!==document.documentElement){const o=getComputedStyle(a).overflowX;if(o!=='visible'){clip=true;break}a=a.parentElement}if(clip)continue;const par=e.parentElement;if(par.getBoundingClientRect().right>w+1&&par!==document.body)continue;out.push(e.tagName+'.'+e.className+' r='+Math.round(r.right)+' '+(e.textContent||'').trim().slice(0,30).replace(/\\s+/g,' '))}return out.slice(0,8)}"""
with sync_playwright() as p:
    b=p.chromium.launch(args=["--no-sandbox"])
    def route(r):
        r.fulfill(status=200,content_type="text/css",body=css)
    for w in (360,375,412,430):
        ctx=b.new_context(viewport={"width":w,"height":900},device_scale_factor=2,is_mobile=True,has_touch=True)
        if out!="voor": ctx.route("**/static/style.css*",route); ctx.route("**/assets/style.css*",route)
        pg=ctx.new_page()
        for path in pages:
            pg.goto(base+path,wait_until="networkidle")
            sw=pg.evaluate("document.documentElement.scrollWidth")
            bad=pg.evaluate(JS,w)
            print(w,path,sw,"OK" if sw<=w and not bad else "OVERFLOW",bad if bad else "")
            if w==412:
                pg.screenshot(path=f"{out}/{path.strip('/').replace('/','_') or 'home'}.png",full_page=False)
        ctx.close()
    b.close()
