#!/bin/bash
# Start headless Chrome for automation
# Usage: ./chrome-start.sh [headless|gui]

MODE="${1:-headless}"
PROFILE="/tmp/chrome-clean"
PORT=9222

# Kill existing
pkill -f "chrome.*$PORT" 2>/dev/null
sleep 1

# Start Chrome
if [ "$MODE" = "gui" ]; then
  DISPLAY=:10 google-chrome \
    --no-sandbox \
    --disable-setuid-sandbox \
    --remote-debugging-port=$PORT \
    --user-data-dir=$PROFILE \
    --no-first-run \
    --password-store=basic \
    about:blank &
else
  google-chrome \
    --headless=new \
    --no-sandbox \
    --disable-setuid-sandbox \
    --remote-debugging-port=$PORT \
    --user-data-dir=$PROFILE \
    --no-first-run \
    --disable-gpu \
    about:blank &
fi

sleep 3

# Verify
if curl -s http://127.0.0.1:$PORT/json/version > /dev/null 2>&1; then
  echo "Chrome ($MODE) running on port $PORT"
  curl -s http://127.0.0.1:$PORT/json/version | jq -r '.Browser'
else
  echo "Failed to start Chrome"
  exit 1
fi
