#!/usr/bin/env bash
# Launch the dedicated Chrome that Jarvis drives over CDP.
#
# Why a separate profile: since Chrome 136 the DEFAULT profile refuses
# remote-debugging for security, and a Playwright/automation-LAUNCHED Chrome
# trips Google's "this browser may not be secure" login block. This script
# launches REAL Chrome yourself (no automation flags) on a dedicated
# --user-data-dir, so you log into your Google accounts once, by hand, and the
# session persists. Jarvis then ATTACHES to it over CDP (never logs in itself),
# which Google is fine with.
#
# First run: log into BOTH Google accounts (personal + alrugaib) in the window
# that opens. They persist in ~/.jarvis-chrome forever. Idempotent: if the
# debug Chrome is already up on the port, this does nothing.
#
# Opens about:blank, NOT Gmail, and does NOT restore the last session. It used to
# launch straight onto mail.google.com, and session-restore then resurrected that
# Gmail tab on every relaunch — so ANY browser task Jarvis did popped the inbox
# onto Ahmed's screen, which his "never open my email" rule forbids. Logins live
# in the profile's cookies, not in restored tabs, so nothing is lost by dropping
# --restore-last-session. The launcher has no business choosing a destination.
set -euo pipefail

PORT="${JARVIS_CHROME_PORT:-9222}"
PROFILE="${JARVIS_CHROME_PROFILE:-$HOME/.jarvis-chrome}"
CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

if curl -s "http://127.0.0.1:${PORT}/json/version" >/dev/null 2>&1; then
  echo "Jarvis Chrome already running on ${PORT}"
  exit 0
fi

if [ ! -x "$CHROME" ]; then
  echo "Google Chrome not found at: $CHROME" >&2
  exit 1
fi

mkdir -p "$PROFILE"
"$CHROME" \
  --remote-debugging-port="$PORT" \
  --user-data-dir="$PROFILE" \
  --no-first-run \
  --no-default-browser-check \
  "about:blank" \
  >/dev/null 2>&1 &
disown

echo "Launched Jarvis Chrome on ${PORT} (profile: $PROFILE)"
