#!/usr/bin/env bash
# Setup helper: install-slack — bundles the preflight + install commands
# from the /add-slack skill into one idempotent script so /new-setup can
# run them programmatically before continuing to credentials.
#
# Copies the Slack adapter in from the `channels` branch; appends the
# self-registration import; installs the pinned @chat-adapter/slack package;
# builds. All steps are safe to re-run.
set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"

# Keep in sync with setup/add-slack.sh.
ADAPTER_VERSION="@chat-adapter/slack@4.26.0"

# Resolve which remote carries the channels branch — forks usually keep the
# installable channel code on upstream rather than origin.
# shellcheck source=setup/lib/channels-remote.sh
source "$PROJECT_ROOT/setup/lib/channels-remote.sh"
CHANNELS_REMOTE=$(resolve_channels_remote)
CHANNELS_BRANCH="${CHANNELS_REMOTE}/channels"

pnpm_cmd() {
  if [ "${1:-}" = "run" ]; then
    pnpm "$@"
    return
  fi
  local store_dir=""
  if [ -f node_modules/.modules.yaml ]; then
    store_dir=$(awk -F'"' '/"storeDir": /{print $4; exit}' node_modules/.modules.yaml)
  fi
  if [ -n "$store_dir" ]; then
    pnpm --store-dir "$store_dir" "$@"
  else
    pnpm "$@"
  fi
}

echo "=== NANOCLAW SETUP: INSTALL_SLACK ==="

needs_install=false
[[ -f src/channels/slack.ts ]] || needs_install=true
grep -q "import './slack.js';" src/channels/index.ts || needs_install=true
grep -q '"@chat-adapter/slack"' package.json || needs_install=true
[[ -d node_modules/@chat-adapter/slack ]] || needs_install=true

if ! $needs_install; then
  echo "STATUS: already-installed"
  echo "=== END ==="
  exit 0
fi

echo "STEP: fetch-channels-branch"
git fetch "$CHANNELS_REMOTE" channels

echo "STEP: copy-files"
git show "${CHANNELS_BRANCH}:src/channels/slack.ts" > src/channels/slack.ts

echo "STEP: register-import"
if ! grep -q "import './slack.js';" src/channels/index.ts; then
  printf "import './slack.js';\n" >> src/channels/index.ts
fi

echo "STEP: pnpm-install"
pnpm_cmd install "${ADAPTER_VERSION}"

echo "STEP: pnpm-build"
pnpm_cmd run build

echo "STATUS: installed"
echo "=== END ==="
