#!/usr/bin/env python3
"""bt: drive a headless Chrome one action at a time, like a Playwright-style browser tool.

  bt.py start | stop
  bt.py open URL
  bt.py snapshot
  bt.py fill CSS TEXT        (clears first)
  bt.py select CSS LABEL     (option by visible text)
  bt.py click CSS           (buttons, checkboxes, radios)
Every action prints a snapshot of the page afterwards: visible headings, fields with values
and errors, and buttons, the way browser tools hand the page back to the agent.
Uses its own temporary Chrome profile, never the user's.
"""
import json, os, subprocess, sys, tempfile, time, urllib.request, glob, shutil

STATE = "/tmp/formlab/bt-state.json"
PORT = 9561

def drv():
    c = sorted(glob.glob(os.path.expanduser("~/.commonshell/drivers/chromedriver-*/**/chromedriver"), recursive=True))
    return c[-1]

def req(method, path, body=None):
    s = json.load(open(STATE))
    url = f"http://127.0.0.1:{PORT}/session/{s['sid']}{path}" if path is not None else f"http://127.0.0.1:{PORT}/session"
    data = json.dumps(body).encode() if body is not None else None
    r = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"})
    try:
        return json.load(urllib.request.urlopen(r, timeout=30))["value"]
    except urllib.error.HTTPError as e:
        v = json.load(e)["value"]
        sys.exit(f"error: {v.get('error')}: {v.get('message','').splitlines()[0]}")

def js(code, *args):
    return req("POST", "/execute/sync", {"script": code, "args": list(args)})

SNAP = r"""
const vis=e=>!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)&&!e.closest('[hidden]');
const out=[];out.push('URL: '+location.href);out.push('Title: '+document.title);
for(const e of document.querySelectorAll('h1,h2,h3,li[aria-current],input,select,textarea,button,p.err,#done-title,#summary dt,#summary dd')){
 if(!vis(e))continue;
 if(e.matches('h1,h2,h3,#done-title'))out.push('heading "'+e.textContent.trim()+'"');
 else if(e.matches('li[aria-current]'))out.push('current step "'+e.textContent.trim()+'"');
 else if(e.matches('p.err')){if(e.textContent)out.push('  error #'+e.id+' "'+e.textContent+'"')}
 else if(e.tagName==='SELECT')out.push('combobox #'+e.id+' value="'+(e.selectedOptions[0]||{}).text+'" options=['+[...e.options].map(o=>o.text).join(', ')+']'+(e.getAttribute('aria-invalid')==='true'?' invalid':''));
 else if(e.tagName==='TEXTAREA')out.push('textarea #'+e.id+' value="'+e.value+'"'+(e.getAttribute('aria-invalid')==='true'?' invalid':''));
 else if(e.tagName==='INPUT'&&e.type==='radio')out.push('radio #'+e.id+' name='+e.name+' "'+((e.closest('label')||{}).textContent||'').trim()+'" checked='+e.checked);
 else if(e.tagName==='INPUT'){const l=document.querySelector('label[for="'+e.id+'"]');out.push((e.type==='checkbox'?'checkbox':'textbox')+' #'+e.id+(l?' "'+l.textContent.trim()+'"':'')+(e.type==='checkbox'?' checked='+e.checked:' value="'+(e.type==='password'?'•'.repeat(e.value.length):e.value)+'"')+(e.getAttribute('aria-invalid')==='true'?' invalid':''))}
 else if(e.tagName==='BUTTON')out.push('button #'+e.id+' "'+e.textContent.trim()+'"');
 else out.push('  '+e.tagName.toLowerCase()+' "'+e.textContent.trim()+'"');
}
return out.join('\n');"""

def snap():
    print(js(SNAP))

def el(css):
    return req("POST", "/element", {"using": "css selector", "value": css})["element-6066-11e4-a52d-4a6a6e4a0e3d"] if False else list(req("POST", "/element", {"using": "css selector", "value": css}).values())[0]

def main():
    a = sys.argv[1:]
    if not a: sys.exit(__doc__)
    cmd = a[0]
    os.makedirs("/tmp/formlab", exist_ok=True)
    if cmd == "start":
        prof = tempfile.mkdtemp(prefix="bt-profile-", dir="/tmp/formlab")
        p = subprocess.Popen([drv(), f"--port={PORT}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        time.sleep(1.2)
        body = {"capabilities": {"alwaysMatch": {"browserName": "chrome", "goog:chromeOptions": {"args": ["--headless=new", f"--user-data-dir={prof}", "--window-size=1100,900", "--no-first-run"]}}}}
        r = urllib.request.Request(f"http://127.0.0.1:{PORT}/session", data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json"})
        sid = json.load(urllib.request.urlopen(r, timeout=60))["value"]["sessionId"]
        json.dump({"sid": sid, "pid": p.pid, "prof": prof}, open(STATE, "w"))
        print("browser started")
    elif cmd == "stop":
        s = json.load(open(STATE))
        try: urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{PORT}/session/{s['sid']}", method="DELETE"), timeout=20)
        except Exception: pass
        try: os.kill(s["pid"], 15)
        except Exception: pass
        shutil.rmtree(s["prof"], ignore_errors=True); os.remove(STATE); print("browser stopped")
    elif cmd == "open":
        req("POST", "/url", {"url": a[1]}); snap()
    elif cmd == "snapshot":
        snap()
    elif cmd == "fill":
        kind = js("const e=document.querySelector(arguments[0]);return e?(e.tagName==='TEXTAREA'?'textarea':e.type):null", a[1])
        if kind is None: sys.exit(f"error: no element {a[1]}")
        if kind in ("date", "month", "time", "datetime-local"):
            js("const e=document.querySelector(arguments[0]);e.value=arguments[1];e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}))", a[1], a[2])
        else:
            e = el(a[1]); req("POST", f"/element/{e}/clear", {}); req("POST", f"/element/{e}/value", {"text": a[2]})
        snap()
    elif cmd == "select":
        ok = js("const s=document.querySelector(arguments[0]);const o=[...s.options].find(o=>o.text===arguments[1]);if(!o)return false;s.value=o.value;s.dispatchEvent(new Event('change',{bubbles:true}));return true", a[1], a[2])
        if not ok: sys.exit(f"error: no option {a[2]!r} in {a[1]}")
        snap()
    elif cmd == "click":
        e = el(a[1]); req("POST", f"/element/{e}/click", {}); time.sleep(0.2); snap()
    else:
        sys.exit(__doc__)

main()
