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

# Type email into the email input field
print("Entering email address...")
result = cdp("Runtime.evaluate", expression="""
    let emailInput = document.getElementById('email-input');
    if (emailInput) {
        emailInput.value = 'beloved.v3l33@gmail.com';
        emailInput.dispatchEvent(new Event('input', {bubbles: true}));
        emailInput.dispatchEvent(new Event('change', {bubbles: true}));
        'Email entered';
    } else {
        'Email input not found';
    }
""", returnByValue=True)
print(result)
sleep(1)
screenshot("/tmp/tm_06_email_entered.png")

# Find and click the Continue button
print("Clicking Continue button...")
result2 = cdp("Runtime.evaluate", expression="""
    let buttons = document.querySelectorAll('button');
    for (let btn of buttons) {
        if (btn.textContent.trim().toLowerCase().includes('continue')) {
            btn.click();
            'Clicked: ' + btn.textContent.trim();
        }
    }
""", returnByValue=True)
print(result2)
sleep(5)
screenshot("/tmp/tm_07_after_continue.png")

# Check what page we're on now
result3 = cdp("Runtime.evaluate", expression="document.body.innerText.substring(0, 3000)", returnByValue=True)
print(f"Page text after continue: {result3}")

result4 = cdp("Runtime.evaluate", expression="""
    let inputs = document.querySelectorAll('input');
    let info = [];
    for (let inp of inputs) {
        info.push({
            type: inp.type,
            name: inp.name,
            id: inp.id,
            placeholder: inp.placeholder,
            visible: inp.offsetParent !== null
        });
    }
    JSON.stringify(info);
""", returnByValue=True)
print(f"Input fields: {result4}")