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
if not rc:
    print("NO RC TARGET"); sys.exit(0)
p=cdp.attach(rc); p.enable()
time.sleep(3)
print("RC url:", p.eval("location.href"))
print("RC title:", p.eval("document.title"))
for _ in range(10):
    body=(p.eval("document.body.innerText") or "")
    if len(body)>80: break
    time.sleep(2)
print("RC body[:1800]:", body[:1800])
# count list rows / report names
counts=p.eval("""(function(){
  var rows=document.querySelectorAll('tr,[class*=row],[class*=report-item],li');
  return JSON.stringify({rowsLike: rows.length});
})()""")
print("COUNTS:", counts)
# find export/csv controls
exp=p.eval("""(function(){
  var hits=[];
  document.querySelectorAll('a,button,[class*=export],[title],[aria-label],i,span').forEach(function(e){
    var s=((e.innerText||'')+' '+(e.title||'')+' '+(e.getAttribute('aria-label')||'')).trim();
    if(/export|csv|download/i.test(s) && s.length<60) hits.push({tag:e.tagName,txt:s.slice(0,50),id:e.id});
  });
  var seen={};var out=[];hits.forEach(function(h){if(!seen[h.txt]){seen[h.txt]=1;out.push(h);}});
  return JSON.stringify(out.slice(0,20));
})()""")
print("EXPORT CONTROLS:", exp)
p.screenshot("/tmp/amd-agent-reportcenter.png")
print("DONE_RC2")
p.close()
