#!/usr/bin/env python3
import json,subprocess,time,urllib.request,sys
from pathlib import Path
URL=sys.argv[1]
OUT=Path(sys.argv[2] if len(sys.argv)>2 else "/home/user/pdf2html-firefox-gate.json")
PORT=4457
proc=subprocess.Popen(["/tmp/geckodriver","--port",str(PORT),"--log","error"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
def req(method,path,payload=None,timeout=60):
    data=None if payload is None else json.dumps(payload).encode()
    r=urllib.request.Request(f"http://127.0.0.1:{PORT}{path}",data=data,method=method,headers={"Content-Type":"application/json"})
    with urllib.request.urlopen(r,timeout=timeout) as x:return json.load(x)
try:
    for _ in range(50):
        try:req("GET","/status",timeout=1);break
        except Exception:time.sleep(.1)
    session=req("POST","/session",{"capabilities":{"alwaysMatch":{"browserName":"firefox","moz:firefoxOptions":{"args":["-headless"],"prefs":{"browser.cache.disk.enable":False,"browser.cache.memory.enable":False,"browser.shell.checkDefaultBrowser":False}}}}},timeout=60)["value"]
    sid=session["sessionId"]
    req("POST",f"/session/{sid}/window/rect",{"width":1400,"height":1000})
    req("POST",f"/session/{sid}/url",{"url":URL},timeout=120)
    script=r"""return (async()=>{await document.fonts.ready;const pages=[...document.querySelectorAll('.pf')],first=pages[0],last=pages[pages.length-1];first.scrollIntoView();await new Promise(r=>setTimeout(r,200));last.scrollIntoView();await new Promise(r=>setTimeout(r,500));const p4=document.querySelector('[data-page-no=\"4\"]');const para=[...p4.querySelectorAll('p')].find(p=>p.textContent.includes('We take pride in our role as a center of excellence'));const list=[...p4.querySelectorAll('ul')].find(u=>u.textContent.includes('End-to-end production supply chain'));const ids=[...document.querySelectorAll('[id]')].map(e=>e.id),dup=[...new Set(ids.filter((x,i,a)=>a.indexOf(x)!==i))];const lr=last.getBoundingClientRect();return {pages:pages.length,visualLines:document.querySelectorAll('.vl').length,paragraphs:document.querySelectorAll('p').length,headings:document.querySelectorAll('h1,h2,h3,h4,h5,h6').length,lists:document.querySelectorAll('ul,ol').length,listItems:document.querySelectorAll('li').length,tables:document.querySelectorAll('table').length,rows:document.querySelectorAll('tr').length,cells:document.querySelectorAll('th,td').length,figures:document.querySelectorAll('.semantic-figure').length,residuals:document.querySelectorAll('.residual-artwork').length,scripts:document.scripts.length,title:document.title,lang:document.documentElement.lang,description:document.querySelector('meta[name=\"description\"]')?.content||'',duplicateIds:dup,p4Lines:para?.querySelectorAll('.vl').length||0,p4ListItems:list?.querySelectorAll('li').length||0,phrase:document.body.innerText.includes('flowers. Our State-of-the-Art facilities use cutting-'),lastRect:{w:lr.width,h:lr.height},contentVisibility:getComputedStyle(first).contentVisibility,remoteResources:performance.getEntriesByType('resource').map(r=>r.name).filter(n=>!n.startsWith(location.origin+'/')),residualPointer:[...document.querySelectorAll('.residual-artwork')].filter(e=>getComputedStyle(e).pointerEvents!=='none').length,loadedLast:[...last.querySelectorAll('img')].every(i=>i.complete&&i.naturalWidth>0)};})()"""
    value=req("POST",f"/session/{sid}/execute/sync",{"script":script,"args":[]},timeout=90)["value"]
    value["firefox"]=session.get("capabilities",{}).get("browserVersion","")
    value["platform"]=session.get("capabilities",{}).get("platformName","")
    OUT.write_text(json.dumps(value,indent=2)+"\n")
    print(json.dumps(value,sort_keys=True))
    expected="ANNUALS & PERENNIALS CATALOG EU & ROW — 2026-28"
    ok=value["pages"]==176 and value["visualLines"]==7128 and value["figures"]==595 and value["residuals"]==176 and value["scripts"]==0 and value["title"]==expected and value["lang"]=="en" and value["description"].startswith(expected) and not value["duplicateIds"] and value["p4Lines"]==5 and value["p4ListItems"]==7 and value["phrase"] and value["lastRect"]=={"w":612,"h":792} and value["contentVisibility"]=="auto" and not value["remoteResources"] and value["residualPointer"]==0 and value["loadedLast"]
    req("DELETE",f"/session/{sid}",{})
    if not ok:sys.exit(2)
finally:
    proc.terminate()
    try:proc.wait(timeout=5)
    except Exception:proc.kill()
