#!/usr/bin/env python3
"""Generate a fresh TOTP and submit it into the MS 'Enter the code' dialog, then
click Next. Prints only NON-SECRET status (whether typed/clicked), never the code
in a way tied to the secret beyond the transient 6 digits needed for the flow.
"""
import sys, json, time
sys.path.insert(0, "/home/claude/repos/openclaw/.claude/skills/advancedmd/scripts")
sys.path.insert(0, "/tmp/amdwork")
import amd_browser as A
import totp_gen

MS = "mysignins.microsoft.com"


def attach():
    for p in A.list_pages():
        if MS in (p.get("url") or ""):
            pg = A.attach(p); pg.enable(); return pg
    raise RuntimeError("no MS tab")


def main():
    code = totp_gen.totp(totp_gen.load_secret())
    pg = attach()
    # find the Code input (by placeholder or type=text visible)
    find_js = ("(function(){var el=document.querySelector('input[placeholder=\"Code\"]')"
               "||Array.from(document.querySelectorAll('input')).find(function(e){return e.offsetParent && (e.type==='text'||e.type==='tel');});"
               "return el;})()")
    jval = json.dumps(code)
    expr = ("(function(){var el=%s; if(!el) return 'NOEL'; el.focus();"
            "var setter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;"
            "setter.call(el,%s);"
            "el.dispatchEvent(new Event('input',{bubbles:true}));"
            "el.dispatchEvent(new Event('change',{bubbles:true}));"
            "return 'TYPED';})()" % (find_js, jval))
    r = pg.eval(expr)
    print("TYPE_CODE", r)
    time.sleep(0.3)
    # click Next via mouse event
    pos = pg.eval("(function(){var els=Array.from(document.querySelectorAll('button'));"
                  "var m=els.find(function(e){return e.offsetParent && (e.innerText||'').trim()==='Next';});"
                  "if(!m) return null; var rc=m.getBoundingClientRect();"
                  "return JSON.stringify({x:rc.left+rc.width/2,y:rc.top+rc.height/2});})()")
    if pos:
        p = json.loads(pos)
        pg.send("Input.dispatchMouseEvent", {"type": "mousePressed", "x": p["x"], "y": p["y"], "button": "left", "clickCount": 1})
        pg.send("Input.dispatchMouseEvent", {"type": "mouseReleased", "x": p["x"], "y": p["y"], "button": "left", "clickCount": 1})
        print("NEXT_CLICKED")
    else:
        print("NEXT_NOTFOUND")
    pg.close()


if __name__ == "__main__":
    main()
