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 focus and type into the email field character by character
print("Focusing email input and typing...")
cdp("Runtime.evaluate", expression="""
    let emailInput = document.getElementById('email-input');
    emailInput.focus();
    emailInput.value = '';
""")

# Type the email using CDP Input.dispatchKeyEvent for more realistic typing
email = "beloved.v3l33@gmail.com"
for char in email:
    cdp("Input.dispatchKeyEvent", type="keyDown", text=char)
    cdp("Input.dispatchKeyEvent", type="keyUp", text=char)
    time.sleep(0.05)

sleep(1)
screenshot("/tmp/tm_08_email_typed.png")

# Verify what's in the field
result = cdp("Runtime.evaluate", expression="document.getElementById('email-input').value", returnByValue=True)
print(f"Email field value: {result}")

# Now click the Continue button using CDP click coordinates
print("Finding and clicking Continue button...")
result2 = cdp("Runtime.evaluate", expression="""
    let buttons = document.querySelectorAll('button');
    let continueBtn = null;
    for (let btn of buttons) {
        if (btn.textContent.trim().toLowerCase().includes('continue')) {
            continueBtn = btn;
            break;
        }
    }
    if (continueBtn) {
        let rect = continueBtn.getBoundingClientRect();
        JSON.stringify({x: rect.x + rect.width/2, y: rect.y + rect.height/2, text: continueBtn.textContent.trim()});
    } else {
        'Continue button not found';
    }
""", returnByValue=True)
print(f"Button location: {result2}")

# Parse the button coordinates
btn_info = json.loads(result2['result']['value'])
x = btn_info['x']
y = btn_info['y']

# Click using CDP mouse events
cdp("Input.dispatchMouseEvent", type="mouseMoved", x=x, y=y)
cdp("Input.dispatchMouseEvent", type="mousePressed", x=x, y=y, button="left", clickCount=1)
cdp("Input.dispatchMouseEvent", type="mouseReleased", x=x, y=y, button="left", clickCount=1)

print("Clicked Continue, waiting for next page...")
sleep(5)
screenshot("/tmp/tm_09_after_continue2.png")

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