import os, sys, json, time

os.environ["BU_NAME"] = "work"
sys.path.insert(0, "/opt/data/browser-harness")
from helpers import goto, wait_for_load, sleep, screenshot, cdp, click, scroll, list_tabs, page_info, new_tab, switch_tab
from admin import daemon_alive, start_remote_daemon

NAME = "work"
assert daemon_alive(NAME), "Browser not alive!"

# Click on email input and type email carefully
print("Clicking email input...")
cdp("Runtime.evaluate", expression="""
    (function() {
        let eml = document.getElementById('email-input');
        if (eml) {
            eml.focus();
            eml.value = '';
            eml.dispatchEvent(new Event('input', {bubbles: true}));
            return 'focused email input';
        }
        return 'email input not found';
    })();
""", returnByValue=True)
time.sleep(0.5)

# Type email using dispatchKeyEvent
email = "beloved.v3l33@gmail.com"
print("Typing email character by character...")
for char in email:
    cdp("Input.dispatchKeyEvent", type="keyDown", text=char)
    time.sleep(0.04)
    cdp("Input.dispatchKeyEvent", type="keyUp", text=char)
    time.sleep(0.02)

time.sleep(1)

# Verify
val = cdp("Runtime.evaluate", expression="document.getElementById('email-input').value", returnByValue=True)
print(f"Email value: {val}")

screenshot("/tmp/cbm_tm_05_email.png")

# Click Continue button
print("Clicking Continue...")
btn_info = cdp("Runtime.evaluate", expression="""
    (function() {
        let allBtns = document.querySelectorAll('button');
        for (let i = 0; i < allBtns.length; i++) {
            if (allBtns[i].textContent.trim().toLowerCase().indexOf('continue') >= 0) {
                let rr = allBtns[i].getBoundingClientRect();
                allBtns[i].click();
                return JSON.stringify({x: rr.x + rr.width/2, y: rr.y + rr.height/2, txt: allBtns[i].textContent.trim()});
            }
        }
        return 'continue button not found';
    })();
""", returnByValue=True)
print(f"Clicked: {btn_info}")

sleep(5)
screenshot("/tmp/cbm_tm_06_after_continue.png")

page_text = cdp("Runtime.evaluate", expression="document.body.innerText.substring(0, 2000)", returnByValue=True)
print(f"Page after continue: {page_text}")