import sys, time, json, urllib.request
sys.path.insert(0, "/tmp/amdwork")
import cdp
LOG="/tmp/amdwork/rc_dom.log"
def log(*a):
    with open(LOG,"a") as f: f.write(" ".join(str(x) for x in a)+"\n")
open(LOG,"w").close()
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()

# dump outerHTML of the category nav area around 'Procedure Codes'
html=p.eval("""(function(){
  var el=Array.from(document.querySelectorAll('*')).find(function(e){return (e.textContent||'').trim()==='Procedure Codes' && e.children.length===0;});
  if(!el) return 'NOEL';
  var row=el; for(var i=0;i<5;i++){ if(row.parentElement){ row=row.parentElement; if(row.querySelectorAll('*').length>2) break; } }
  return row.outerHTML.slice(0,1200);
})()""")
log("ROW HTML:", html)

# Try the search box approach: type 'Provider' and capture results
sb=p.eval("""(function(){
  var i=document.querySelector('input[placeholder*=Find],input[type=text],input[type=search]');
  if(!i) return 'NOSEARCH';
  Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set.call(i,'Provider');
  i.dispatchEvent(new Event('input',{bubbles:true}));
  i.dispatchEvent(new Event('keyup',{bubbles:true}));
  return 'TYPED';
})()""")
log("search typed:", sb)
time.sleep(3)
res=p.eval("""(function(){
  function vis(e){var r=e.getBoundingClientRect();return r.width>0&&r.height>0;}
  var out=[];
  document.querySelectorAll('a,li,div,span').forEach(function(e){
    if(!vis(e))return; if(e.children.length>1)return;
    var t=(e.innerText||'').trim();
    if(t && t.length>4 && t.length<70) out.push(t);
  });
  return JSON.stringify(Array.from(new Set(out)).slice(0,50));
})()""")
log("search results:", res)
p.screenshot("/tmp/amdwork/rc-search.png")
log("DONE_DOM")
p.close()
