import sys, time, json, urllib.request, os
sys.path.insert(0, "/tmp/amdwork")
import cdp
LOG="/tmp/amdwork/rc_export.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"]

# Re-assert download behavior at browser level (in case)
ver=json.loads(urllib.request.urlopen("http://localhost:9223/json/version",timeout=10).read())
import websocket
bws=websocket.create_connection(ver["webSocketDebuggerUrl"],timeout=30,max_size=None); _bid=[0]
def bsend(method,params=None):
    _bid[0]+=1; mid=_bid[0]
    bws.send(json.dumps({"id":mid,"method":method,"params":params or {}}))
    while True:
        m=json.loads(bws.recv())
        if m.get("id")==mid: return m
bsend("Browser.setDownloadBehavior",{"behavior":"allow","downloadPath":"/home/claude/amd-agent-downloads","eventsEnabled":True})

rc=None
for t in targets():
    if "/reportcenter/" in (t.get("url") or ""): rc=t; break
p=cdp.attach(rc); p.enable()
log("RC url:", p.eval("location.href"))

DLDIR="/home/claude/amd-agent-downloads"
before_files=set(os.listdir(DLDIR))
log("files before:", json.dumps(sorted(before_files)))

# 1) Select All providers (ensure data)
sa=p.eval("""(function(){
  var b=Array.from(document.querySelectorAll('a,button,span')).find(function(e){return (e.innerText||'').trim()==='Select All';});
  if(b){b.click(); return 'selectAll clicked';} return 'no selectAll';
})()""")
log("select all:", sa)
time.sleep(1)

# 2) Choose CSV format radio/label
csv=p.eval("""(function(){
  // find element whose text mentions CSV(COMMA DELIMITED)
  var lbl=Array.from(document.querySelectorAll('label,span,div,a,td')).find(function(e){return /CSV\\s*\\(COMMA/i.test((e.innerText||'')) && e.children.length<=1;});
  if(!lbl) return 'NOCSV';
  // click associated radio if present, else click the label
  var radio=lbl.querySelector('input[type=radio]');
  if(!radio && lbl.previousElementSibling && lbl.previousElementSibling.type==='radio') radio=lbl.previousElementSibling;
  if(!radio){ var forid=lbl.getAttribute('for'); if(forid) radio=document.getElementById(forid); }
  if(radio){ radio.click(); return 'csv radio clicked checked='+radio.checked; }
  lbl.click(); return 'csv label clicked';
})()""")
log("csv format:", csv)
time.sleep(1)

# 3) Enable 'Export on Run' toggle
eor=p.eval("""(function(){
  var lbl=Array.from(document.querySelectorAll('label,span,div')).find(function(e){return /Export on Run/i.test((e.innerText||'')) && e.children.length<=2;});
  if(!lbl) return 'NO_EOR';
  var cb=lbl.querySelector('input[type=checkbox]');
  if(!cb && lbl.previousElementSibling && lbl.previousElementSibling.type==='checkbox') cb=lbl.previousElementSibling;
  if(!cb){var forid=lbl.getAttribute('for'); if(forid) cb=document.getElementById(forid);}
  if(!cb){ // search nearby
     var p=lbl.parentElement; if(p) cb=p.querySelector('input[type=checkbox]');
  }
  if(cb){ if(!cb.checked) cb.click(); return 'EOR checked='+cb.checked; }
  lbl.click(); return 'EOR label clicked';
})()""")
log("export on run:", eor)
time.sleep(1)

# 4) Click Run Report
rr=p.eval("""(function(){
  var b=Array.from(document.querySelectorAll('button,a,input[type=button],input[type=submit]')).find(function(e){return /Run Report/i.test((e.innerText||e.value||''));});
  if(!b) return 'NORUN';
  b.click(); return 'RUN clicked';
})()""")
log("run report:", rr)

# 5) Wait for download to land (poll dir up to 60s)
deadline=time.time()+60
newfiles=set()
while time.time()<deadline:
    cur=set(os.listdir(DLDIR))
    newfiles=cur-before_files
    done=[f for f in newfiles if not f.endswith(".crdownload")]
    if done:
        break
    time.sleep(2)
log("new files:", json.dumps(sorted(newfiles)))
for f in sorted(newfiles):
    fp=os.path.join(DLDIR,f)
    try:
        sz=os.path.getsize(fp)
        log("FILE:", f, "size:", sz)
        if f.lower().endswith(".csv"):
            with open(fp,"r",errors="replace") as fh:
                lines=fh.read().splitlines()
            log("CSV rows(incl header):", len(lines))
            log("CSV header:", json.dumps(lines[0][:200] if lines else ""))
            if len(lines)>1:
                log("CSV row1 sample:", json.dumps(lines[1][:200]))
    except Exception as e:
        log("size err:", str(e)[:120])
log("url after run:", p.eval("location.href"))
p.screenshot("/tmp/amdwork/rc-after-run.png")
log("SHOT:/tmp/amdwork/rc-after-run.png")
log("DONE_EXPORT")
p.close(); bws.close()
