#!/usr/bin/env bash
set -euo pipefail

# Argument interception for profile selection
# `$@` contains the original arguments passed to the script

NEW_ARGS=()
for arg in "$@"; do
    if [[ "$arg" == --user-data-dir=* ]]; then
        # If the provided profile path contains "Antigravity", swap it for the specialized profile
        if [[ "$arg" == *"Antigravity"* ]]; then
            arg="--user-data-dir=$HOME/.gemini/antigravity-browser-profile"
        else
            # Otherwise, use the standard fallback profile for non-Antigravity users
            arg="--user-data-dir=$HOME/.var/app/com.google.Chrome/config/google-chrome/vscode-debug-profile"
        fi
    fi
    NEW_ARGS+=("$arg")
done

# Prefer Flatpak Chrome if installed, else fall back to system Chrome/Chromium.
if [ -x "$HOME/.local/share/flatpak/exports/bin/com.google.Chrome" ]; then
  exec "$HOME/.local/share/flatpak/exports/bin/com.google.Chrome" "${NEW_ARGS[@]}"
elif [ -x "/var/lib/flatpak/exports/bin/com.google.Chrome" ]; then
  exec "/var/lib/flatpak/exports/bin/com.google.Chrome" "${NEW_ARGS[@]}"
elif command -v google-chrome-stable >/dev/null 2>&1; then
  exec google-chrome-stable "${NEW_ARGS[@]}"
elif command -v google-chrome >/dev/null 2>&1; then
  exec google-chrome "${NEW_ARGS[@]}"
elif command -v chromium >/dev/null 2>&1; then
  exec chromium "${NEW_ARGS[@]}"
elif command -v chromium-browser >/dev/null 2>&1; then
  exec chromium-browser "${NEW_ARGS[@]}"
else
  echo "No Chrome/Chromium found. Install Google Chrome/Chromium or Flatpak com.google.Chrome" >&2
  exit 1
fi