import sys, time
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"]

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

# inspect form
print("FIELDS:", p.eval("""(function(){
  var inputs=Array.from(document.querySelectorAll('input')).map(function(i){return {type:i.type,name:i.name,id:i.id,checked:(i.type==='radio'||i.type==='checkbox')?i.checked:undefined,val:i.value};});
  return JSON.stringify(inputs);
})()"""))

def set_input(selector, value):
    js="""(function(){
      var el=document.querySelector(%r); if(!el) return 'NOFIELD';
      var proto=window.HTMLInputElement.prototype;
      Object.getOwnPropertyDescriptor(proto,'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';
    })()""" % (selector,value)
    return p.eval(js)

print("loginName:", set_input("input#loginName", user))
print("officeKey:", set_input("input#officeKey", office))
print("password:", "set" if set_input("input#password", pw)=="OK" else "FAIL")

# PM radio: click + force checked + dispatch change
pm = p.eval("""(function(){
  var r=document.querySelector('input[name=applications][value=pm]');
  if(!r) return 'NOPM';
  r.click();
  if(!r.checked){
    var proto=window.HTMLInputElement.prototype;
    var d=Object.getOwnPropertyDescriptor(proto,'checked');
    if(d&&d.set) d.set.call(r,true); else r.checked=true;
    r.dispatchEvent(new Event('click',{bubbles:true}));
    r.dispatchEvent(new Event('input',{bubbles:true}));
    r.dispatchEvent(new Event('change',{bubbles:true}));
  }
  return r.checked ? 'CHECKED' : 'NOTCHECKED';
})()""")
print("pm radio:", pm)
time.sleep(1)
print("verify loginName:", p.eval("(document.querySelector('input#loginName')||{}).value"))
print("verify officeKey:", p.eval("(document.querySelector('input#officeKey')||{}).value"))
print("verify pw len:", p.eval("(document.querySelector('input#password')||{value:''}).value.length"))
print("verify pm checked:", p.eval("(function(){var r=document.querySelector('input[name=applications][value=pm]'); return r?r.checked:'none';})()"))
p.screenshot("/tmp/amdwork/login2-filled.png")

print("submit:", p.eval("(function(){var b=document.querySelector('button[type=submit]'); if(b){b.click(); return 'clicked';} return 'NOBTN';})()"))
deadline=time.time()+15; url=None; body=None
while time.time()<deadline:
    time.sleep(2)
    url=p.eval("location.href"); body=(p.eval("document.body.innerText") or "")
    if "/login" not in url and "#/login" not in url:
        break
print("url after:", url)
print("title after:", p.eval("document.title"))
print("body after:", (body or "")[:1200])
p.screenshot("/tmp/amdwork/after-login2-submit.png")
print("DONE2")
p.close()
