import sys, time, json, urllib.request
sys.path.insert(0, "/tmp/amdwork")
import cdp

LOG = "/tmp/amdwork/launch_pm.log"
def log(*a):
    with open(LOG, "a") as f:
        f.write(" ".join(str(x) for x in a) + "\n")
open(LOG, "w").close()

creds={}
for line in open("/home/claude/.config/amd-agent/credentials.env"):
    line=line.strip()
    if "=" in line and not line.startswith("AMD_SECQ"):
        k,v=line.split("=",1); creds[k]=v
user=creds["AMD_USER"]; office=creds["AMD_OFFICE"]; pw=creds["AMD_PASSWORD"]

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})
log("download behavior set -> /home/claude/amd-agent-downloads")

def targets():
    return [t for t in json.loads(urllib.request.urlopen("http://localhost:9223/json",timeout=10).read()) if t.get("type")=="page"]

before=set(t.get("id") for t in targets())
p=cdp.attach(targets()[0])
p.enable()
p.navigate("https://static-100.advancedmd.com/apps/login/#/launch-app")
time.sleep(7)
url=p.eval("location.href"); log("after nav launch-app:", url)
log("body:", json.dumps((p.eval("document.body.innerText") or "")[:400]))

def set_input(sel,val):
    return p.eval("""(function(){var el=document.querySelector(%r);if(!el)return'NOFIELD';
      Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set.call(el,%r);
      el.dispatchEvent(new Event('input',{bubbles:true}));el.dispatchEvent(new Event('change',{bubbles:true}));el.dispatchEvent(new Event('blur',{bubbles:true}));return'OK';})()""" % (sel,val))

if "#/login" in url or p.eval("!!document.querySelector('input#loginName')"):
    log("login form detected -> filling")
    set_input("input#loginName",user); set_input("input#officeKey",office); set_input("input#password",pw)
    pm=p.eval("(function(){var r=document.querySelector('input#pm[name=applications]')||document.querySelector('input[name=applications][value=pm]'); if(r){ if(!r.checked)r.click(); if(!r.checked){var d=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'checked'); if(d&&d.set)d.set.call(r,true); r.dispatchEvent(new Event('change',{bubbles:true}));} return r.checked;} return 'none';})()")
    log("pm checked:", pm)
    time.sleep(1)
    p.eval("(function(){var b=document.querySelector('button[type=submit]'); if(b)b.click();})()")
    time.sleep(7)
    url=p.eval("location.href"); log("after login submit:", url)

if "confirm-email" in url:
    p.screenshot("/tmp/amd-agent-mfa.png")
    el=p.eval("""(function(){
      function vis(e){var r=e.getBoundingClientRect();return r.width>0&&r.height>0;}
      var cbs=Array.from(document.querySelectorAll('input[type=checkbox]')).filter(vis).map(function(c){
        var lbl='';
        if(c.id){var l=document.querySelector('label[for=\"'+c.id+'\"]'); if(l)lbl=l.innerText.trim();}
        if(!lbl && c.closest('label')) lbl=c.closest('label').innerText.trim();
        return {id:c.id,name:c.name,checked:c.checked,label:lbl.slice(0,80)};
      });
      return JSON.stringify(cbs);
    })()""")
    log("confirm-email checkboxes(trust-device?):", el)
    log("confirm-email body:", json.dumps((p.eval("document.body.innerText") or "")[:500]))
    # Use Confirm later to proceed past email-confirm (it is optional)
    p.eval("""(function(){var b=Array.from(document.querySelectorAll('button')).find(function(x){return x.innerText.trim().toLowerCase().indexOf('confirm later')>=0;}); if(b)b.click(); return 'cl';})()""")
    time.sleep(7)
    url=p.eval("location.href"); log("after confirm-later:", url)
    log("body after CL:", json.dumps((p.eval("document.body.innerText") or "")[:400]))

# If compat dialog present, close it (popups now allowed so PM should open)
if "launch-app" in url:
    log("at launch-app; closing any compat dialog (popups allowed now)")
    p.eval("(function(){var b=Array.from(document.querySelectorAll('button')).find(function(x){return x.innerText.trim().toLowerCase()==='close';}); if(b)b.click(); return 'ok';})()")
    time.sleep(8)

after=targets()
new=[t for t in after if t.get("id") not in before]
log("NEW TARGETS (popups/PM windows):")
for t in new:
    log("  NEW:", t.get("url"))
log("ALL TARGETS:")
for t in after:
    log("  ", t.get("url"))
log("MAIN PAGE FINAL URL:", p.eval("location.href"))
p.screenshot("/tmp/amdwork/launch-pm-state.png")
log("DONE_LAUNCHPM")
p.close(); bws.close()
