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!"

# Use CDP to click the email input, then type using dispatchKeyEvent
print("Clicking on email input field...")
cdp("Runtime.evaluate", expression="""
    let eml = document.getElementById('email-input');
    if (eml) {
        let r = eml.getBoundingClientRect();
        window.__emailRect = {x: r.x + r.width/2, y: r.y + r.height/2};
        eml.focus();
        eml.value = '';
        'found email input at ' + JSON.stringify(window.__emailRect);
    } else {
        'email input not found';
    }
""", returnByValue=True)

# Click on the email field
eml_rect_raw = cdp("Runtime.evaluate", expression="JSON.stringify(window.__emailRect)", returnByValue=True)
print(f"Email rect: {eml_rect_raw}")
eml_rect = json.loads(eml_rect_raw['result']['value'])
cdp("Input.dispatchMouseEvent", type="mouseMoved", x=eml_rect['x'], y=eml_rect['y'])
cdp("Input.dispatchMouseEvent", type="mousePressed", x=eml_rect['x'], y=eml_rect['y'], button="left", clickCount=1)
cdp("Input.dispatchMouseEvent", type="mouseReleased", x=eml_rect['x'], y=eml_rect['y'], button="left", clickCount=1)
time.sleep(0.5)

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

time.sleep(1)
screenshot("/tmp/tm_10_email_typed2.png")

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

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

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

page_url = cdp("Runtime.evaluate", expression="window.location.href", returnByValue=True)
print(f"URL: {page_url}")