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

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"]

# Browser ws to capture all targets (popups)
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})

p=cdp.attach(cdp.find_target("advancedmd") or cdp.find_target())
p.enable()
p.navigate("https://static-100.advancedmd.com/apps/identity/#/login/a17b81eb-c5fe-4a67-89be-e79304c33e76")
time.sleep(6)
print("login url:", p.eval("location.href"))

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))
set_input("input#loginName",user); set_input("input#officeKey",office); set_input("input#password",pw)
print("pm checked:", p.eval("(function(){var r=document.querySelector('input#pm[name=applications]'); if(r&&!r.checked)r.click(); return r?r.checked:'none';})()"))
p.eval("(function(){var b=document.querySelector('button[type=submit]'); if(b)b.click();})()")
time.sleep(7)
url=p.eval("location.href"); print("after submit:", url)

# confirm-email -> confirm later
if "confirm-email" in url:
    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(6)
    url=p.eval("location.href"); print("after confirm-later:", url)

# Now we should be on launch-app. Override window.open to capture target URL.
if "launch-app" in url:
    # install hook then close compat dialog and re-trigger
    p.eval("""(function(){window.__pmUrl=null; var o=window.open; window.open=function(u,n,f){window.__pmUrl=u; return o.call(window,u,n,f);}; return 'hooked';})()""")
    # close compat
    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(3)
    captured=p.eval("window.__pmUrl")
    print("captured pmUrl (from prior open):", captured)
    # also dump any script-embedded launch url
    dump=p.eval("""(function(){
      var txt=document.documentElement.innerHTML;
      var m=txt.match(/https?:\\/\\/[^"'\\s<>]*amplugin[^"'\\s<>]*/i) || txt.match(/https?:\\/\\/[^"'\\s<>]*launch[^"'\\s<>]*/i);
      return m?m[0]:'NOMATCH';
    })()""")
    print("html-scan launch url:", dump)

print("ALL PAGES:")
for t in json.loads(urllib.request.urlopen("http://localhost:9223/json",timeout=10).read()):
    if t.get("type")=="page": print("  ", t.get("url"))
p.screenshot("/tmp/amdwork/full-launch-state.png")
print("DONE")
p.close(); bws.close()
