#!/usr/bin/env bash
#
# Archie MCP + skills installer for Cursor, Claude, and ChatGPT desktop / Codex.
#
# Usage (interactive):
#   ./integrations/install.sh
#   ./integrations/install.sh --client=claude
#   ./integrations/install.sh --client=all
#
# Usage (remote install — no clone required):
#   curl -fsSL https://archie-install.lonelyplanet.com/install.sh | bash
#   curl -fsSL .../install.sh | bash -s -- --client=chatgpt --non-interactive
#
# Flags:
#   --client=NAME         cursor | claude | chatgpt | all (repeatable; default cursor)
#   --non-interactive     Read tokens from ARCHIE_TOKEN_* env vars
#   --project DIR         Project-scoped MCP + guidelines (tokens as env placeholders)
#   --no-skills           Skip installing agent skills
#   --uninstall           Remove Archie MCP entries and skills for selected client(s)
#
# Claude Desktop needs Node.js/npx for the mcp-remote bridge. The installer
# reuses an existing Node when it can find one; otherwise it asks before using a
# package manager and falls back to a private copy under ~/.archie/node.
#   ARCHIE_SKIP_NODE_INSTALL=true   Never install Node; fail if npx is missing
#   ARCHIE_AUTO_INSTALL_NODE=true   Allow package-manager installs when --non-interactive
#   ARCHIE_NODE_VERSION=22.14.0     Node version for the private install
#   ARCHIE_NODE_PREFIX=~/.archie/node
#   ARCHIE_MCP_REMOTE_VERSION=0.1.38
#
set -euo pipefail

ARCHIE_CDN_URL_DEFAULT="https://archie-install.lonelyplanet.com"

_resolve_install_lib() {
  local dir tmp
  if [[ -n "${BASH_SOURCE[0]:-}" ]]; then
    dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)" || dir=""
    if [[ -n "$dir" && -f "$dir/common/install-lib.sh" ]]; then
      printf '%s\n' "$dir/common/install-lib.sh"
      return 0
    fi
  fi
  if ! command -v curl >/dev/null 2>&1; then
    err() { echo "error: $*" >&2; }
    err "curl is required for remote install"
    exit 1
  fi
  tmp="$(mktemp "${TMPDIR:-/tmp}/archie-install-lib.XXXXXX")"
  curl -sfL --max-time 30 "${ARCHIE_CDN_URL:-$ARCHIE_CDN_URL_DEFAULT}/common/install-lib.sh" -o "$tmp"
  printf '%s\n' "$tmp"
}

INSTALL_LIB="$(_resolve_install_lib)"
# shellcheck source=/dev/null
source "$INSTALL_LIB"

CLIENT_ARG=""
# PROJECT_DIR / INSTALL_SKILLS / NON_INTERACTIVE / UNINSTALL are consumed by install-lib.sh.
# shellcheck disable=SC2034
while [[ $# -gt 0 ]]; do
  case "$1" in
    --non-interactive) NON_INTERACTIVE=true ;;
    --project) PROJECT_DIR="${2:-}"; shift ;;
    --project=*) PROJECT_DIR="${1#*=}" ;;
    --no-skills) INSTALL_SKILLS=false ;;
    --uninstall) UNINSTALL=true ;;
    --client) CLIENT_ARG="${2:-}"; shift ;;
    --client=*) CLIENT_ARG="${1#*=}" ;;
    -h|--help)
      sed -n '2,31p' "$0"
      exit 0
      ;;
    *) warn "ignoring unknown argument: $1" ;;
  esac
  shift
done

detect_script_mode "$0"

if [[ -n "$CLIENT_ARG" ]]; then
  parse_install_clients_spec "$CLIENT_ARG"
elif [[ -n "${ARCHIE_INSTALL_CLIENTS:-}" ]]; then
  parse_install_clients_spec "$ARCHIE_INSTALL_CLIENTS"
elif [[ "$NON_INTERACTIVE" == "true" ]]; then
  INSTALL_CLIENTS=(cursor)
else
  select_clients_interactive
fi

if [[ "$UNINSTALL" == "true" ]]; then
  echo ""
  info "Uninstalling Archie for: ${INSTALL_CLIENTS[*]}"
  for client in "${INSTALL_CLIENTS[@]}"; do
    run_client_uninstall "$client"
  done
  echo ""
  ok "Archie uninstall complete for: ${INSTALL_CLIENTS[*]}"
  exit 0
fi

select_environments "selected clients"
collect_tokens
run_probes "Archie"

failed=()
client=""
for client in "${INSTALL_CLIENTS[@]}"; do
  echo ""
  info "Installing Archie for $client..."
  if run_client_install "$client"; then
    :
  else
    failed+=("$client")
  fi
done

echo ""
echo "${GREEN}============================================${NC}"
if [[ ${#failed[@]} -eq 0 ]]; then
  echo "${GREEN}  Archie setup complete${NC}"
else
  echo "${YELLOW}  Archie setup completed with errors${NC}"
  warn "Failed clients: ${failed[*]}"
fi
echo "${GREEN}============================================${NC}"
print_token_reminders "your AI client(s)"

for client in "${INSTALL_CLIENTS[@]}"; do
  print_client_next_steps "$client"
done

if [[ ${#failed[@]} -gt 0 ]]; then
  exit 1
fi
