#!/bin/bash
set -euo pipefail

CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
SOURCE="$HOME/Library/Application Support/Google/Chrome"
PROFILE="$HOME/Library/Application Support/Google/Chrome-Hermes"
AGENT_BROWSER="$HOME/.hermes/hermes-agent/node_modules/.bin/agent-browser"
CDP_PORT=9222
DASHBOARD_PORT=4848
# Browser automation deliberately never uses Default/Adolfo's Chrome profile.
CHROME_PROFILE="Profile 1"

require_tools() {
  test -x "$CHROME"
  test -x "$AGENT_BROWSER"
}

clone_profile_once() {
  if test -f "$PROFILE/Local State"; then
    return
  fi
  mkdir -p "$PROFILE"
  rsync -a \
    --exclude='Cache' \
    --exclude='Code Cache' \
    --exclude='GPUCache' \
    --exclude='GrShaderCache' \
    --exclude='ShaderCache' \
    --exclude='Service Worker/CacheStorage' \
    --exclude='Service Worker/ScriptCache' \
    --exclude='Media Cache' \
    --exclude='Singleton*' \
    --exclude='LOCK' \
    --exclude='*.lock' \
    "$SOURCE/" "$PROFILE/"
}

start() {
  require_tools
  clone_profile_once
  if ! curl -fsS --max-time 2 "http://127.0.0.1:${CDP_PORT}/json/version" >/dev/null; then
    open -na "Google Chrome" --args \
      --remote-debugging-address=127.0.0.1 \
      --remote-debugging-port="$CDP_PORT" \
      --remote-allow-origins='*' \
      --user-data-dir="$PROFILE" \
      --profile-directory="$CHROME_PROFILE" \
      --no-first-run \
      --no-default-browser-check \
      --disable-search-engine-choice-screen \
      --new-window about:blank
    for _ in $(seq 1 20); do
      curl -fsS --max-time 1 "http://127.0.0.1:${CDP_PORT}/json/version" >/dev/null && break
      sleep 1
    done
  fi
  curl -fsS --max-time 2 "http://127.0.0.1:${CDP_PORT}/json/version" >/dev/null
  "$AGENT_BROWSER" dashboard start --port "$DASHBOARD_PORT" >/dev/null 2>&1 || true
  "$AGENT_BROWSER" connect "$CDP_PORT" --session hermes-visible >/dev/null
  printf 'Browser automation ready. Dashboard: http://127.0.0.1:%s\n' "$DASHBOARD_PORT"
}

status() {
  printf 'CDP: '
  curl -fsS --max-time 2 "http://127.0.0.1:${CDP_PORT}/json/version" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("Browser", "up"))' || echo 'down'
  printf 'Dashboard: '
  curl -fsS --max-time 2 -o /dev/null -w '%{http_code}\n' "http://127.0.0.1:${DASHBOARD_PORT}/" || echo 'down'
  printf 'Profile: %s\n' "$PROFILE"
}

case "${1:-}" in
  start) start ;;
  status) status ;;
  *) echo "Usage: $(basename "$0") {start|status}" >&2; exit 2 ;;
esac
