import sys, time, json, urllib.request
sys.path.insert(0, "/tmp/amdwork")
import cdp

def pages():
    return [t for t in json.loads(urllib.request.urlopen("http://localhost:9223/json",timeout=10).read()) if t.get("type")=="page"]

print("BEFORE PAGES:")
for p in pages(): print("  ", p.get("url"))

# reload launch-app to retrigger window.open
pg = cdp.attach(cdp.find_target("launch-app"))
pg.enable()
# try calling window.open directly is blocked w/o gesture; instead reload
pg.eval("location.reload()")
time.sleep(8)
# close compat dialog if present
try:
    pg.eval("(function(){var b=Array.from(document.querySelectorAll('button')).find(function(x){return x.innerText.trim().toLowerCase()==='close';}); if(b)b.click(); return 'ok';})()")
except Exception as e:
    print("reattach needed:", e)
time.sleep(3)

print("AFTER PAGES:")
for p in pages(): print("  ", p.get("url"))
pg.close()
print("DONE")
