#!/bin/bash
# Per-agent Android emulators for QA (AVDs qa1, qa2 from android-setup.sh).
#   up <avd> <port>            boot headless on an even port (5554, 5556), prints serial
#   reverse <serial> <port>    make the Mac's localhost:<port> reachable in the emulator
#   open <serial> <url>        open url in Chrome
#   cdp <serial> <local port>  forward Chrome DevTools, prints the CDP url
#   shot <serial> <file.png>   screenshot
#   tap-text <serial> <text>   tap the first element whose text or content-desc contains <text>
#   texts <serial>             list visible texts with their tap centers
#   down <serial>              stop the emulator
set -euo pipefail
AH="${ANDROID_HOME:-$(brew --prefix)/share/android-commandlinetools}"
export PATH="$AH/platform-tools:$AH/emulator:$PATH"

# Prints "x y<TAB>text" for every node with text or content-desc.
nodes() {
  # The dump fails with "null root node" while the UI is still settling: retry.
  for _ in 1 2 3 4 5 6; do
    adb -s "$1" shell uiautomator dump /sdcard/qa-ui.xml 2>&1 | grep -q "dumped to" && break
    sleep 2
  done
  adb -s "$1" exec-out cat /sdcard/qa-ui.xml | python3 -c '
import re, sys, xml.etree.ElementTree as ET
for n in ET.fromstring(sys.stdin.read()).iter("node"):
    label = n.get("text") or n.get("content-desc") or ""
    m = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", n.get("bounds", ""))
    if label and m:
        x1, y1, x2, y2 = map(int, m.groups())
        print(f"{(x1 + x2) // 2} {(y1 + y2) // 2}\t{label}")'
}

cmd="${1:-}"
case "$cmd" in
  up)
    avd="${2:?avd}"; port="${3:?even port}"; serial="emulator-$port"
    nohup emulator -avd "$avd" -no-window -no-audio -no-boot-anim -port "$port" \
      >"/tmp/qa-$avd.log" 2>&1 &
    adb -s "$serial" wait-for-device
    until [ "$(adb -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do sleep 2; done
    echo "$serial"
    ;;
  reverse) adb -s "${2:?serial}" reverse "tcp:${3:?port}" "tcp:$3" >/dev/null ;;
  open)
    adb -s "${2:?serial}" shell am start -a android.intent.action.VIEW -d "${3:?url}" com.android.chrome >/dev/null
    ;;
  cdp)
    # Chrome's DevTools socket on the Mac's localhost:<port>, for
    # playwright-cli attach --cdp=http://localhost:<port> --session=<name>
    adb -s "${2:?serial}" forward "tcp:${3:?local port}" localabstract:chrome_devtools_remote >/dev/null
    echo "http://localhost:$3"
    ;;
  shot) adb -s "${2:?serial}" exec-out screencap -p > "${3:?file}"; echo "$3" ;;
  texts) nodes "${2:?serial}" ;;
  tap-text)
    hit=$(nodes "${2:?serial}" | grep -F -m1 -- "${3:?text}" || true)
    [ -n "$hit" ] || { echo "no element with text: $3" >&2; exit 1; }
    adb -s "$2" shell input tap ${hit%%$'\t'*}
    echo "tapped ${hit}"
    ;;
  down) adb -s "${2:?serial}" emu kill >/dev/null ;;
  *) sed -n '2,10p' "$0"; exit 1 ;;
esac
