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"]
pm=None
for t in targets():
    if "/pm/app/" in (t.get("url") or ""): pm=t; break
p=cdp.attach(pm); p.enable()
# Full body text scan for AGENT and office, plus iframes
res=p.eval("""(function(){
  function grab(doc){
    var out={};
    out.text = (doc.body? doc.body.innerText : '');
    return out;
  }
  var main=grab(document);
  var frames=[];
  document.querySelectorAll('iframe').forEach(function(f){
    try{ frames.push({src:f.src, text:(f.contentDocument&&f.contentDocument.body)?f.contentDocument.body.innerText.slice(0,400):'(noaccess)'}); }
    catch(e){ frames.push({src:f.src, text:'(crossorigin)'}); }
  });
  return JSON.stringify({hasAGENT: /\\bAGENT\\b/.test(main.text), has161112: main.text.indexOf('161112')>=0, frames:frames});
})()""")
print("RES:", res)
# Search the whole DOM HTML for AGENT token in header attributes/title
hdr=p.eval("""(function(){
  var html=document.documentElement.innerHTML;
  var idx=html.toUpperCase().indexOf('AGENT');
  var snip = idx>=0 ? html.substring(Math.max(0,idx-80), idx+40) : 'NOTFOUND';
  // also check document.title and any tooltip
  return JSON.stringify({title:document.title, agentSnip:snip});
})()""")
print("HDR:", hdr)
# AMD often exposes user in a global or cookie
glob=p.eval("""(function(){
  try{
    var keys=Object.keys(window).filter(function(k){return /user|login|profile|context/i.test(k);});
    return JSON.stringify(keys.slice(0,20));
  }catch(e){return 'err';}
})()""")
print("GLOBALS:", glob)
p.screenshot("/tmp/amd-agent-dashboard.png")
print("DONE_WHO")
p.close()
