import sys, time, json, urllib.request
sys.path.insert(0, "/tmp/amdwork")
import cdp
def targets():
    return [t for t in json.loads(urllib.request.urlopen("http://localhost:9223/json",timeout=10).read()) if t.get("type")=="page"]
rc=None
for t in targets():
    if "/reportcenter/" in (t.get("url") or ""): rc=t; break
p=cdp.attach(rc); p.enable()
print("url:", p.eval("location.href"))

# click 'Procedure Codes' category
r=p.eval("""(function(){
  var el=Array.from(document.querySelectorAll('a,span,li,div')).find(function(e){return (e.innerText||'').trim()==='Procedure Codes';});
  if(!el) return 'NOCAT';
  el.click(); return 'clicked Procedure Codes';
})()""")
print("cat:", r)
time.sleep(4)
print("url after cat:", p.eval("location.href"))
# list reports now visible
reports=p.eval("""(function(){
  var out=[];
  document.querySelectorAll('a,li,[class*=report],[class*=item],h4,h5,td').forEach(function(e){
    var s=(e.innerText||'').trim();
    if(s && s.length<70 && s.length>3) out.push(s);
  });
  var seen={};var u=[];out.forEach(function(s){if(!seen[s]){seen[s]=1;u.push(s);}});
  return JSON.stringify(u.slice(0,40));
})()""")
print("REPORTS:", reports)
p.screenshot("/tmp/amdwork/rc-procedure-codes.png")
print("DONE_EXP")
p.close()
