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 Sign In/Register
print("Looking for Sign In button...")
result = cdp("Runtime.evaluate", expression="""
    // Find sign in link
    let links = document.querySelectorAll('a');
    let signInLink = null;
    for (let a of links) {
        if (a.textContent.trim().toLowerCase().includes('sign in')) {
            signInLink = a;
            break;
        }
    }
    if (signInLink) {
        signInLink.click();
        'Clicked sign in link: ' + signInLink.href;
    } else {
        // Try buttons
        let btns = document.querySelectorAll('button');
        let btnTexts = [];
        for (let b of btns) {
            btnTexts.push(b.textContent.trim());
        }
        'No sign in link found. Buttons: ' + btnTexts.join(', ');
    }
""", returnByValue=True)
print(result)
sleep(5)
screenshot("/tmp/tm_04_signin.png")

# Check where we are now
result2 = cdp("Runtime.evaluate", expression="window.location.href", returnByValue=True)
print(f"URL after sign in click: {result2}")

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