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

# First, search for BTS on Ticketmaster SG
print("Searching for BTS on Ticketmaster SG...")
goto("https://www.ticketmaster.sg/search?query=BTS")
wait_for_load()
sleep(5)
screenshot("/tmp/tm_02_search.png")

# Get page content to find BTS event links
result = cdp("Runtime.evaluate", expression="""
    let results = [];
    document.querySelectorAll('a[href*="event"], a[href*="BTS"], a[href*="bts"]').forEach(a => {
        results.push({text: a.textContent.trim().substring(0, 100), href: a.href});
    });
    // Also get all links on the page for debugging
    let allLinks = [];
    document.querySelectorAll('a').forEach(a => {
        if (a.textContent.trim() && a.href.includes('ticketmaster')) {
            allLinks.push({text: a.textContent.trim().substring(0, 80), href: a.href});
        }
    });
    JSON.stringify({search_results: results.slice(0, 20), all_links: allLinks.slice(0, 40)});
""", returnByValue=True)
print(f"Search results: {result}")

# Also get the full page text to understand what we see
result2 = cdp("Runtime.evaluate", expression="document.body.innerText.substring(0, 3000)", returnByValue=True)
print(f"Page text: {result2}")