#!/usr/bin/env bash
#
# Install the AI Bridge native-messaging host so the Chrome extension's
# "Start/Stop Bridge" button can launch bridge/server.py.
#
# Usage:
#   bash bridge/install_native_host.sh <EXTENSION_ID>
#
# Find <EXTENSION_ID> at chrome://extensions (Developer mode → the ID under
# "AI Bridge"). It stays stable for an unpacked extension as long as the
# extension folder path doesn't change.
#
# Re-run this after moving the repo or reloading the extension with a new ID.

set -euo pipefail

HOST_NAME="com.aibridge.launcher"
EXT_ID="${1:-}"

if [[ -z "$EXT_ID" ]]; then
  echo "error: pass the extension ID as the first argument."
  echo "  find it at chrome://extensions (Developer mode) under 'AI Bridge'."
  echo "  usage: bash bridge/install_native_host.sh <EXTENSION_ID>"
  exit 1
fi

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LAUNCHER="$HERE/launcher.py"

if [[ ! -f "$LAUNCHER" ]]; then
  echo "error: launcher not found at $LAUNCHER"
  exit 1
fi

# Chrome must be able to execute the launcher directly.
chmod +x "$LAUNCHER"

# Native-messaging host manifest locations differ by browser + OS.
case "$(uname -s)" in
  Darwin)
    declare -a TARGET_DIRS=(
      "$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
      "$HOME/Library/Application Support/Google/Chrome Canary/NativeMessagingHosts"
      "$HOME/Library/Application Support/Chromium/NativeMessagingHosts"
      "$HOME/Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts"
    )
    ;;
  Linux)
    declare -a TARGET_DIRS=(
      "$HOME/.config/google-chrome/NativeMessagingHosts"
      "$HOME/.config/chromium/NativeMessagingHosts"
      "$HOME/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts"
    )
    ;;
  *)
    echo "error: unsupported OS $(uname -s). Install the manifest manually."
    exit 1
    ;;
esac

MANIFEST_JSON=$(cat <<EOF
{
  "name": "$HOST_NAME",
  "description": "AI Bridge local server launcher",
  "path": "$LAUNCHER",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://$EXT_ID/"
  ]
}
EOF
)

installed=0
for dir in "${TARGET_DIRS[@]}"; do
  parent="$(dirname "$dir")"
  # Only install into browsers that are actually present on this machine.
  if [[ -d "$parent" ]]; then
    mkdir -p "$dir"
    printf '%s\n' "$MANIFEST_JSON" > "$dir/$HOST_NAME.json"
    echo "installed → $dir/$HOST_NAME.json"
    installed=$((installed + 1))
  fi
done

if [[ "$installed" -eq 0 ]]; then
  echo "warning: no supported browser profile dirs found; nothing installed."
  exit 1
fi

echo
echo "done. Reload the AI Bridge extension, then use the Start/Stop Bridge"
echo "button in the side panel. Launcher: $LAUNCHER (python: repo .venv if present)."
