#!/usr/bin/env bash
# remote-browser — read a Chromium browser running on another machine, over CDP.
#
# Works for any host the agent can reach (an SSH alias, or a direct address) whose
# browser exposes a CDP endpoint. Chrome-family browsers expose one when the user ticks
#   chrome://inspect/#remote-debugging → "Allow remote debugging for this browser instance"
# which serves ONLY ws://127.0.0.1:<port>/devtools/browser (HTTP /json/* returns 403).
# Playwright attaches to a ws:// endpoint directly, so this is a thin wrapper that opens
# the tunnel and drives `playwright-cli`. Setup for a new device: see references/setup.md
# in the remote-browser skill, and run `remote-browser check`.
#
#   remote-browser profiles                     list configured devices
#   remote-browser setup --name deck --host deck [--port 9222] [--transport ssh]
#   remote-browser check [--profile deck]        step-by-step readiness test
#   remote-browser tabs | status | text | html | shot
#   remote-browser cli <playwright-cli args>     full passthrough to playwright-cli
#                                                (console, requests, storage, tracing,
#                                                run-code, pdf, tab-*, goto/click…);
#                                                ours flags are not parsed after `cli`
#   remote-browser cli -- <args>                 explicit end-of-options form
#
# Options: --profile/-p NAME, --index N, --match SUBSTR, --limit CHARS, --out FILE.
# Read-only by intent: no click/type/navigate helper exists, because driving an
# authenticated session is what gets accounts restricted.
#
# Env: REMOTE_BROWSER_PROFILE (default profile), REMOTE_BROWSER_DIR (config dir).
set -euo pipefail

CONF_DIR=${REMOTE_BROWSER_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/remote-browser}
PROFILE_DIR="$CONF_DIR/profiles"
PN=$(basename "$0")

die() { echo "$PN: $*" >&2; exit 1; }
info() { echo "  $*" >&2; }

usage() { sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }

# --- argument parsing ---------------------------------------------------------

PROFILE=${REMOTE_BROWSER_PROFILE:-}
CMD=""
ARGS=()
while [ $# -gt 0 ]; do
  if [ -n "$CMD" ] && [ "$CMD" = cli ]; then
    # `cli` is a full passthrough: everything after it belongs to playwright-cli,
    # including flags that look like ours.
    ARGS+=("$1"); shift; continue
  fi
  case "$1" in
    --profile|-p) PROFILE=${2:-}; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    --) shift; if [ -z "$CMD" ]; then CMD=${1:-}; shift; fi
        while [ $# -gt 0 ]; do ARGS+=("$1"); shift; done ;;
    *) if [ -z "$CMD" ]; then CMD=$1; else ARGS+=("$1"); fi; shift ;;
  esac
done

# --- profiles -----------------------------------------------------------------

profile_file() { echo "$PROFILE_DIR/$1.env"; }

load_profile() {
  [ -n "$PROFILE" ] || die "no profile given (use --profile NAME, or set REMOTE_BROWSER_PROFILE). Try: $PN profiles"
  local f; f=$(profile_file "$PROFILE")
  [ -f "$f" ] || die "unknown profile '$PROFILE' ($f missing). Try: $PN profiles"
  # shellcheck disable=SC1090
  . "$f"
  : "${RB_HOST:?profile $f has no RB_HOST}"
  RB_PORT=${RB_PORT:-9222}
  RB_TRANSPORT=${RB_TRANSPORT:-ssh}
  RB_WS_PATH=${RB_WS_PATH:-/devtools/browser}
  RB_INSPECT_URL=${RB_INSPECT_URL:-chrome://inspect/#remote-debugging}
  SESSION="rb-$PROFILE"
  if [ "$RB_TRANSPORT" = ssh ]; then
    WS="ws://127.0.0.1:${RB_PORT}${RB_WS_PATH}"
  else
    WS="ws://${RB_HOST}:${RB_PORT}${RB_WS_PATH}"
  fi
}

list_profiles() {
  [ -d "$PROFILE_DIR" ] || { echo "no profiles yet — create one with: $PN setup --name <name> --host <host>"; return 0; }
  shopt -s nullglob
  local found=0 f
  for f in "$PROFILE_DIR"/*.env; do
    found=1
    ( . "$f"
      printf '%-12s %-6s %-24s %s:%s\n' \
        "$(basename "$f" .env)" "${RB_TRANSPORT:-ssh}" "${RB_HOST:-?}" "${RB_HOST:-?}" "${RB_PORT:-9222}" )
  done
  [ $found -eq 1 ] || echo "no profiles yet — create one with: $PN setup --name <name> --host <host>"
}

# --- transport ----------------------------------------------------------------

port_open() { (exec 3<>"/dev/tcp/${1}/${2}") 2>/dev/null; }

host_reachable() {
  case "$RB_TRANSPORT" in
    ssh) ssh -o BatchMode=yes -o ConnectTimeout=6 "$RB_HOST" true >/dev/null 2>&1 ;;
    direct) port_open "$RB_HOST" "$RB_PORT" ;;
    *) return 1 ;;
  esac
}

ensure_tunnel() {
  if [ "$RB_TRANSPORT" = direct ]; then
    port_open "$RB_HOST" "$RB_PORT" || die "cannot reach ${RB_HOST}:${RB_PORT} (transport=direct)"
    return 0
  fi
  port_open 127.0.0.1 "$RB_PORT" && return 0
  ssh -o BatchMode=yes -o ExitOnForwardFailure=yes -f -N \
      -L "${RB_PORT}:127.0.0.1:${RB_PORT}" "$RB_HOST" 2>/dev/null \
    || die "cannot open SSH tunnel to ${RB_HOST} — is it awake and is your key authorised?"
  for _ in $(seq 1 25); do port_open 127.0.0.1 "$RB_PORT" && return 0; sleep 0.2; done
  die "tunnel up but nothing listening on 127.0.0.1:${RB_PORT}.
  On ${RB_HOST}, open ${RB_INSPECT_URL} and tick
  'Allow remote debugging for this browser instance', then retry."
}

ws_handshake() { # prints HTTP status line of a WS upgrade attempt
  python3 - "${1}" <<'PY' 2>/dev/null || echo "no-response"
import base64, os, socket, sys, urllib.parse as up
url = up.urlparse(sys.argv[1])
s = socket.create_connection((url.hostname, url.port or 80), timeout=5)
key = base64.b64encode(os.urandom(16)).decode()
s.sendall((f"GET {url.path or '/'} HTTP/1.1\r\nHost: {url.hostname}:{url.port}\r\n"
           "Upgrade: websocket\r\nConnection: Upgrade\r\n"
           f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
print(s.recv(256).decode(errors="replace").split("\r\n")[0].strip() or "no-response")
s.close()
PY
}

ensure_attached() {
  ensure_tunnel
  playwright-cli -s="$SESSION" eval '1' >/dev/null 2>&1 && return 0
  playwright-cli -s="$SESSION" attach --cdp="$WS" >/dev/null 2>&1 \
    || die "playwright-cli could not attach to ${WS}.
  On ${RB_HOST}: open ${RB_INSPECT_URL} and tick
  'Allow remote debugging for this browser instance'."
}

# --- helpers ------------------------------------------------------------------

# tab_list → "INDEX<TAB>TITLE<TAB>URL"
tab_list() {
  playwright-cli -s="$SESSION" tab-list 2>/dev/null \
    | sed -n 's/^- \([0-9]\+\): \(.*\)\[\(.*\)\](\(.*\))$/\1\t\3\t\4/p'
}

resolve_tab() {
  local idx="" match=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --index) idx=${2:-}; shift 2 ;;
      --match) match=${2:-}; shift 2 ;;
      *) shift ;;
    esac
  done
  if [ -n "$match" ]; then
    idx=$(tab_list | awk -F'\t' -v m="$(printf '%s' "$match" | tr 'A-Z' 'a-z')" \
          'tolower($0) ~ m {print $1; exit}')
    [ -n "$idx" ] || die "no tab matching '$match'"
  fi
  printf '%s' "${idx:-}"
}

json_unquote() {
  python3 -c '
import json, sys
for line in sys.stdin.read().splitlines():
    line = line.strip()
    if line[:1] == chr(34) and line[-1:] == chr(34):
        try:
            sys.stdout.write(json.loads(line)); break
        except Exception:
            pass
'
}

# --- commands -----------------------------------------------------------------

cmd_setup() {
  local name="" host="" port=9222 transport=ssh path=/devtools/browser inspect=""
  local url_default
  while [ $# -gt 0 ]; do
    case "$1" in
      --name) name=${2:-}; shift 2 ;;
      --host) host=${2:-}; shift 2 ;;
      --port) port=${2:-}; shift 2 ;;
      --transport) transport=${2:-}; shift 2 ;;
      --ws-path) path=${2:-}; shift 2 ;;
      --inspect-url) inspect=${2:-}; shift 2 ;;
      *) die "setup: unexpected argument '$1'" ;;
    esac
  done
  [ -n "$name" ] || die "setup: --name is required (a short label, e.g. deck, laptop)"
  [ -n "$host" ] || die "setup: --host is required (ssh alias or address)"
  case "$transport" in ssh|direct) ;; *) die "setup: --transport must be ssh or direct" ;; esac
  mkdir -p "$PROFILE_DIR"
  local f; f=$(profile_file "$name")
  if [ -f "$f" ]; then
    info "updating existing profile $name ($f)"
  fi
  cat > "$f" <<EOF
# remote-browser profile created $(date -Iseconds) by \`$PN setup\`
# transport=ssh forwards the remote loopback port to 127.0.0.1 locally.
# transport=direct talks to RB_HOST:RB_PORT as-is (no tunnel).
RB_TRANSPORT=$transport
RB_HOST=$host
RB_PORT=$port
RB_WS_PATH=$path
RB_INSPECT_URL=${inspect:-chrome://inspect/#remote-debugging}
EOF
  chmod 600 "$f"
  echo "wrote $f"
  echo
  echo "Next: on $host, open ${inspect:-chrome://inspect/#remote-debugging} and tick"
  echo "      'Allow remote debugging for this browser instance', then run:"
  echo "        $PN check --profile $name"
}

cmd_check() {
  load_profile
  local failures=0
  say() { printf '%s %s\n' "$1" "$2"; }
  [ -n "$PROFILE" ] && printf 'profile: %s  (transport=%s host=%s port=%s)\n\n' "$PROFILE" "$RB_TRANSPORT" "$RB_HOST" "$RB_PORT"

  if [ "$RB_TRANSPORT" = ssh ]; then
    if ssh -o BatchMode=yes -o ConnectTimeout=6 "$RB_HOST" true >/dev/null 2>&1; then
      say "✓" "ssh to $RB_HOST works"
    else
      say "✗" "ssh to $RB_HOST failed — add an ssh config entry and key, or use --transport direct"
      failures=$((failures+1))
    fi
  fi

  if ensure_tunnel 2>/dev/null; then
    say "✓" "cdp port reachable at $( [ "$RB_TRANSPORT" = ssh ] && echo "127.0.0.1:$RB_PORT via tunnel" || echo "$RB_HOST:$RB_PORT" )"
  else
    say "✗" "cdp port not reachable — is the browser running with remote debugging enabled?"
    say " " "  on $RB_HOST: open $RB_INSPECT_URL and tick the box"
    failures=$((failures+1))
  fi

  if [ $failures -eq 0 ]; then
    local status; status=$(ws_handshake "$WS")
    case "$status" in
      *" 101"*) say "✓" "websocket handshake on ${RB_WS_PATH} accepted" ;;
      *) say "✗" "websocket handshake returned '${status}'"
         say " " "  expected 101; a 403/404 means the endpoint is not the CDP socket"
         failures=$((failures+1)) ;;
    esac
  fi

  if [ $failures -eq 0 ] && ensure_attached 2>/dev/null; then
    say "✓" "playwright attached (session $SESSION)"
    local ua; ua=$(playwright-cli -s="$SESSION" eval 'navigator.userAgent' 2>/dev/null | json_unquote)
    say "✓" "browser: ${ua:-unknown}"
    local n; n=$(tab_list | wc -l)
    if [ "$n" -gt 0 ]; then
      say "✓" "$n tab(s) visible — try: $PN tabs --profile $PROFILE"
    else
      say "!" "attached but no tabs found (open a page in that browser)"
    fi
  elif [ $failures -eq 0 ]; then
    say "✗" "playwright could not attach to $WS"
    failures=$((failures+1))
  fi

  echo
  if [ $failures -eq 0 ]; then
    echo "ready. Read-only commands: tabs, text, html, shot, status, cli."
    return 0
  fi
  echo "$failures check(s) failed."
  return 1
}

case "$CMD" in
  ""|-h|--help) usage; exit 0 ;;
  profiles) list_profiles ;;
  setup) cmd_setup "${ARGS[@]+"${ARGS[@]}"}" ;;
  check) cmd_check ;;
  tabs)
    load_profile; ensure_attached
    tab_list | awk -F'\t' '{printf "%2s  %-52s  %s\n", $1, substr($2,1,52), $3}'
    ;;
  status)
    load_profile; ensure_attached
    playwright-cli -s="$SESSION" eval 'navigator.userAgent' | json_unquote
    ;;
  text|html)
    LIMIT=8000; tabargs=()
    while [ ${#ARGS[@]} -gt 0 ]; do
      case "${ARGS[0]}" in
        --limit) LIMIT=${ARGS[1]:-8000}; ARGS=("${ARGS[@]:2}") ;;
        *) tabargs+=("${ARGS[0]}"); ARGS=("${ARGS[@]:1}") ;;
      esac
    done
    load_profile; ensure_attached
    idx=$(resolve_tab "${tabargs[@]+"${tabargs[@]}"}")
    [ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
    if [ "$CMD" = text ]; then expr='document.body.innerText'; else expr='document.documentElement.outerHTML'; fi
    out=$(playwright-cli -s="$SESSION" eval "$expr" | json_unquote)
    printf '%s' "$out" | head -c "$LIMIT"
    [ "${#out}" -gt "$LIMIT" ] && printf '\n[truncated %s more characters]\n' "$(( ${#out} - LIMIT ))"
    echo
    ;;
  shot)
    OUT=/tmp/remote-browser-$(date +%s).png; tabargs=()
    while [ ${#ARGS[@]} -gt 0 ]; do
      case "${ARGS[0]}" in
        --out) OUT=${ARGS[1]:-$OUT}; ARGS=("${ARGS[@]:2}") ;;
        *) tabargs+=("${ARGS[0]}"); ARGS=("${ARGS[@]:1}") ;;
      esac
    done
    load_profile; ensure_attached
    idx=$(resolve_tab "${tabargs[@]+"${tabargs[@]}"}")
    [ -n "$idx" ] && playwright-cli -s="$SESSION" tab-select "$idx" >/dev/null
    playwright-cli -s="$SESSION" screenshot --filename="$OUT" >/dev/null
    echo "$OUT"
    ;;
  cli)
    load_profile; ensure_attached
    playwright-cli -s="$SESSION" "${ARGS[@]+"${ARGS[@]}"}"
    ;;
  *)
    die "unknown command '$CMD'. Try: $PN --help"
    ;;
esac
