#!/usr/bin/env bash
# background-web-control — background DOM automation for Chrome/Edge tabs.
#
# Cross-platform launcher: dispatches to the per-OS implementation.
#   macOS  -> components/macos/browser-automation/background_web_control.py (Apple Events + CDP)
#   Linux  -> components/linux/browser-automation/background_web_control.py (CDP + MV3 native bridge)
# Argv/stdout/stderr/exit-code are passed through unchanged. Auto-repair guards
# must remain enabled (forbidden flags are rejected here, same as the guard wrapper).
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "$0")" && pwd -P)"
ROOT_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd -P)"

PY=python3
case "$(uname -s)" in
  Darwin) COMPONENT="$ROOT_DIR/components/macos/browser-automation/background_web_control.py" ;;
  Linux)
    COMPONENT="$ROOT_DIR/components/linux/browser-automation/background_web_control.py"
    # Optional per-host config (e.g. non-default Chrome user-data-dir / force-installed
    # extension id) so native-transport commands auto-target the right profile.
    if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/HelperAI/helperai.env" ]; then
      # shellcheck disable=SC1090
      . "${XDG_CONFIG_HOME:-$HOME/.config}/HelperAI/helperai.env"
    fi
    ;;
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    # Git Bash / MSYS on Windows: dispatch to the Windows component, which the
    # bin/background-web-control.bat launcher also targets. Python is exposed as
    # `python` (not `python3`) in a standard Windows install.
    COMPONENT="$ROOT_DIR/components/windows/browser-automation/background_web_control.py"
    # Native Windows python can't read MSYS-style (/d/...) paths, so hand it a
    # Windows path.
    if command -v cygpath >/dev/null 2>&1; then
      COMPONENT="$(cygpath -w "$COMPONENT")"
    fi
    PY=python
    ;;
  *) echo "error: background-web-control: unsupported OS: $(uname -s)" >&2; exit 64 ;;
esac

for arg in "$@"; do
  case "$arg" in
    --no-auto-repair-js-channel|--no-auto-repair-debugger-bridge)
      echo "error: forbidden flag: $arg — auto-repair guards must remain enabled." >&2
      exit 64
      ;;
  esac
done

exec /usr/bin/env "$PY" "$COMPONENT" "$@"
