#!/usr/bin/env python3
"""Open the Curogram change-password (activation) URL in the agent chrome and
inspect the form. Stage 'inspect' just dumps fields; stage 'fill' fills+submits
the password (read from creds, never printed)."""
import sys, json, time, os
sys.path.insert(0, "/home/claude/repos/openclaw/.claude/skills/advancedmd/scripts")
import amd_browser as A

CHPWD = "https://app.curogram.com/change-password/CHPWD-46556c006-fe77-4717-8d08-a067a51602c6"
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_IN_CREDS")

stage = sys.argv[1] if len(sys.argv) > 1 else "inspect"

# Use the about:blank tab (or reuse an app.curogram.com tab if present).
t = A.find_target(url_sub="app.curogram.com") or A.find_target(want_blank=True) or A.list_pages()[-1]
pg = A.attach(t); pg.enable()

if stage == "nav" or stage == "inspect":
    if "app.curogram.com/change-password" not in (pg.eval("location.href") or ""):
        A.goto(pg, CHPWD, settle=4)
    print("URL:", pg.eval("location.href"))
    print("TITLE:", pg.eval("document.title"))
    print("INPUTS:", json.dumps(A.list_inputs(pg)))
    print("CLICKABLES:", json.dumps(A.list_clickables(pg, limit=40)))
    print("BODY:", (pg.eval("(document.body&&document.body.innerText||'').slice(0,600)")))

elif stage == "fill":
    pw = get_pw()
    # Set every visible password field to pw (handles 'new' + 'confirm').
    n = pg.eval(
      "(()=>{const ps=[...document.querySelectorAll('input[type=password]')];"
      "const setter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;"
      "ps.forEach(p=>{p.focus();setter.call(p,%s);"
      "p.dispatchEvent(new Event('input',{bubbles:true}));"
      "p.dispatchEvent(new Event('change',{bubbles:true}));"
      "p.dispatchEvent(new KeyboardEvent('keyup',{bubbles:true}));});"
      "return ps.length;})()" % json.dumps(pw)
    )
    print("FILLED_PW_FIELDS:", n)
    time.sleep(1)
    # Show field count + any validation text, then DO NOT submit yet (separate stage).
    print("BODY_AFTER_FILL:", (pg.eval("(document.body&&document.body.innerText||'').slice(0,600)")))

elif stage == "submit":
    # Click the primary submit/save button.
    clicked = pg.eval(
      "(()=>{const b=[...document.querySelectorAll('button,input[type=submit],a[role=button]')]"
      ".find(x=>x.offsetParent && /save|set password|submit|change password|continue|confirm|reset/i.test((x.innerText||x.value||'')));"
      "if(!b) return 'NOBTN:'+[...document.querySelectorAll('button')].map(x=>x.innerText.trim()).join('|');"
      "b.click(); return 'CLICKED:'+(b.innerText||b.value||'').trim();})()"
    )
    print("SUBMIT:", clicked)
    time.sleep(5)
    print("URL_AFTER:", pg.eval("location.href"))
    print("BODY_AFTER:", (pg.eval("(document.body&&document.body.innerText||'').slice(0,700)")))

pg.close()
