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

EXTENSION_DIR="${ADDC_BROWSER_HELPER_DIR:-/opt/addc-companion-headless/autodarts-browser-helper}"
PROFILE_DIR="${HOME}/.addc-companion-headless/chromium-profile"
URL="${1:-https://play.autodarts.io}"

if [[ -z "${DISPLAY:-}" && -z "${WAYLAND_DISPLAY:-}" ]]; then
  echo "No Pi desktop display was found."
  echo "ADDC Companion is still running, but Autodarts must be opened in a browser on the Pi desktop for live capture."
  echo "Use VNC, plug in a screen, or keep manual result backup enabled in the ADDC app."
  exit 1
fi

BROWSER=""
for candidate in chromium-browser chromium google-chrome google-chrome-stable; do
  if command -v "${candidate}" >/dev/null 2>&1; then
    BROWSER="${candidate}"
    break
  fi
done

if [[ -z "${BROWSER}" ]]; then
  echo "Chromium or Chrome was not found. Install Chromium, then run addc-autodarts again."
  exit 1
fi

mkdir -p "${PROFILE_DIR}"

exec "${BROWSER}" \
  --user-data-dir="${PROFILE_DIR}" \
  --disable-extensions-except="${EXTENSION_DIR}" \
  --load-extension="${EXTENSION_DIR}" \
  --start-maximized \
  "${URL}"
