"""Type into the explore search box and report what the grid shows."""
import json, os, subprocess, sys, time, urllib.request

URL = sys.argv[1]
TOKEN = sys.argv[2]
TERM = sys.argv[3] if len(sys.argv) > 3 else "Beta"
CHROME = ("/tmp/claude-0/-root-alhang/4ab098a2-a126-4502-b30c-c3d7b59e8765/scratchpad/"
          "chs/chrome-headless-shell-linux64/chrome-headless-shell")
PORT = 9224

src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "cdp.py")).read()
ns = {}
exec(src[src.index("class WS"):src.index("EVENTS = []")], {
    "base64": __import__("base64"), "json": json, "secrets": __import__("secrets"),
    "socket": __import__("socket"), "struct": __import__("struct"),
    "time": time, "EVENTS": []}, ns)
WS = ns["WS"]

proc = subprocess.Popen(
    [CHROME, "--remote-debugging-port=%d" % PORT, "--no-sandbox", "--disable-gpu",
     "--disable-dev-shm-usage", "--window-size=1400,900", "about:blank"],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    target = None
    for _ in range(50):
        time.sleep(0.4)
        try:
            with urllib.request.urlopen("http://127.0.0.1:%d/json" % PORT, timeout=3) as r:
                pages = [t for t in json.loads(r.read()) if t.get("type") == "page"]
            if pages:
                target = pages[0]; break
        except Exception:
            continue
    ws = WS(target["webSocketDebuggerUrl"])
    ws.call("Runtime.enable"); ws.call("Page.enable")
    ws.call("Page.addScriptToEvaluateOnNewDocument",
            {"source": 'try{localStorage.setItem("token",%s)}catch(e){}'
                       % json.dumps(json.dumps(TOKEN))})

    def ev(expr, timeout=25):
        r = ws.call("Runtime.evaluate", {"expression": expr, "returnByValue": True},
                    timeout=timeout)
        res = r.get("result", {})
        if res.get("exceptionDetails"):
            return "EXC " + json.dumps(res["exceptionDetails"])[:160]
        return res.get("result", {}).get("value")

    ws.call("Page.navigate", {"url": URL})
    time.sleep(16)
    print("title  :", ev("document.title"))
    print("inputs :", ev("Array.from(document.querySelectorAll('input'))"
                         ".map(function(i){return i.placeholder||i.type}).join(' | ')"))
    print("click  :", ev("""
      (function(){
        var els = Array.from(document.querySelectorAll('button'));
        var d = els.filter(function(e){return /^Download$/i.test((e.textContent||'').trim());})[0];
        if(!d){return 'no Download button';}
        d.click();
        return 'clicked Download';
      })()"""))
    time.sleep(9)
    print("modal  :", json.dumps(ev(
        "(document.body.innerText||'').replace(/\\n+/g,' | ').slice(-700)"))[:900])
    print("links  :", ev(
        "Array.from(document.querySelectorAll('a')).map(function(a){return a.href;})"
        ".filter(function(h){return /download|discord\\.com|apple|google/i.test(h);}).slice(0,8).join(' , ')"))
finally:
    proc.terminate()
