#!/bin/sh
# Platfory one-line installer.
# Installs the Platfory extension into VS Code, Cursor, VSCodium, or Windsurf.
# It finds your editor even if the `code`/`cursor` command isn't on your PATH,
# so you don't have to fiddle with the Extensions UI. Inspectable and safe:
#   curl -fsSL https://www.platfory.ai/install.sh | sh
# Prefer to read it first? Download, open it, then run `sh install.sh`.

set -eu

VSIX_URL="https://www.platfory.ai/platfory-extension.vsix"
# The editor's --install-extension requires a filename ending in .vsix, so use a
# temp directory with a proper name rather than a bare mktemp file.
TMPDIR_P="$(mktemp -d)" || { echo "platfory: could not create temp dir"; exit 1; }
TMP="$TMPDIR_P/platfory-extension.vsix"
trap 'rm -rf "$TMPDIR_P"' EXIT

echo "Platfory: downloading the extension..."
curl -fsSL "$VSIX_URL" -o "$TMP"

# Find an editor CLI: first on PATH, then in the usual app locations (macOS/Linux).
find_editor() {
  for c in cursor code codium windsurf code-insiders; do
    if command -v "$c" >/dev/null 2>&1; then command -v "$c"; return 0; fi
  done
  for p in \
    "/Applications/Cursor.app/Contents/Resources/app/bin/cursor" \
    "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code" \
    "/Applications/VSCodium.app/Contents/Resources/app/bin/codium" \
    "/Applications/Windsurf.app/Contents/Resources/app/bin/windsurf" \
    "$HOME/.local/bin/cursor" "$HOME/.local/bin/code" \
    "/usr/bin/code" "/usr/share/code/bin/code" "/snap/bin/code" \
    "/usr/bin/codium" "/usr/bin/cursor"; do
    if [ -x "$p" ]; then echo "$p"; return 0; fi
  done
  return 1
}

if EDITOR_BIN="$(find_editor)"; then
  echo "Platfory: installing into $EDITOR_BIN"
  # Remove any prior version first so old copies don't pile up and confuse sign-in.
  "$EDITOR_BIN" --uninstall-extension platfory.platfory-ai >/dev/null 2>&1 || true
  "$EDITOR_BIN" --install-extension "$TMP" --force
  echo ""
  echo "Done. IMPORTANT: reload your editor window (Command Palette -> 'Developer: Reload Window'),"
  echo "then run 'Platfory: Sign in' and complete it in the browser."
else
  echo ""
  echo "Platfory: couldn't find VS Code / Cursor / VSCodium / Windsurf automatically."
  echo "The extension is downloaded here: $TMP"
  echo "Open your editor's Extensions panel and use 'Install from VSIX...' with that file,"
  echo "or see https://www.platfory.ai/install for other options."
  trap - EXIT   # keep the file so the user can install it manually
fi
