#!/usr/bin/env python3
"""Retype the Curogram password using real CDP keystrokes (Input.insertText) so
Angular reactive-form validators register the value. Then submit.
Never prints the password."""
import sys, json, time
sys.path.insert(0, "/home/claude/repos/openclaw/.claude/skills/advancedmd/scripts")
import amd_browser as A

CREDS = "/home/claude/.config/amd-agent/credentials.env"
def get_pw():
    with open(CREDS) as f:
        for ln in f:
            if ln.startswith("CUROGRAM_AGENT_PASSWORD="):
                return ln.split("=", 1)[1].strip()
    raise SystemExit("NO_PW")

t = A.find_target(url_sub="app.curogram.com")
pg = A.attach(t); pg.enable()
pw = get_pw()

def field_center(idx):
    pos = pg.eval(
      "(()=>{const ps=[...document.querySelectorAll('input[type=password]')];"
      "if(ps.length<=%d) return null; const r=ps[%d].getBoundingClientRect();"
      "return JSON.stringify({x:r.left+r.width/2,y:r.top+r.height/2});})()" % (idx, idx)
    )
    return json.loads(pos) if pos else None

def clear_and_type(idx):
    c = field_center(idx)
    if not c:
        print("NO_FIELD", idx); return False
    # Click to focus
    pg.send("Input.dispatchMouseEvent", {"type":"mousePressed","x":c["x"],"y":c["y"],"button":"left","clickCount":1})
    pg.send("Input.dispatchMouseEvent", {"type":"mouseReleased","x":c["x"],"y":c["y"],"button":"left","clickCount":1})
    time.sleep(0.2)
    # Select-all + delete to clear any prior synthetic value
    pg.send("Input.dispatchKeyEvent", {"type":"keyDown","modifiers":2,"key":"a","code":"KeyA"})
    pg.send("Input.dispatchKeyEvent", {"type":"keyUp","modifiers":2,"key":"a","code":"KeyA"})
    pg.send("Input.dispatchKeyEvent", {"type":"keyDown","key":"Delete","code":"Delete"})
    pg.send("Input.dispatchKeyEvent", {"type":"keyUp","key":"Delete","code":"Delete"})
    time.sleep(0.1)
    # Real text insertion
    pg.send("Input.insertText", {"text": pw})
    time.sleep(0.2)
    # Fire blur so validators run
    pg.eval("(()=>{const ps=[...document.querySelectorAll('input[type=password]')];"
            "ps[%d].dispatchEvent(new Event('blur',{bubbles:true}));return true;})()" % idx)
    return True

print("F0", clear_and_type(0))
print("F1", clear_and_type(1))
time.sleep(0.5)
# Report whether values are now present (length only) + any visible validation text.
lens = pg.eval("JSON.stringify([...document.querySelectorAll('input[type=password]')].map(p=>p.value.length))")
print("VALUE_LENS:", lens)
print("PRE_SUBMIT_BODY:", pg.eval("(document.body&&document.body.innerText||'').slice(0,400)"))

# Submit
clicked = pg.eval(
  "(()=>{const b=[...document.querySelectorAll('button')].find(x=>x.offsetParent&&/submit/i.test(x.innerText));"
  "if(!b) return 'NOBTN'; b.click(); return 'CLICKED';})()"
)
print("SUBMIT:", clicked)
time.sleep(6)
print("URL_AFTER:", pg.eval("location.href"))
print("BODY_AFTER:", pg.eval("(document.body&&document.body.innerText||'').slice(0,500)"))
pg.close()
