#!/usr/bin/env bash
set -euo pipefail

CLI_PACKAGE="@usesocial/cli@latest"
SKILL_PACKAGE="usesocial/skill"
SKILL_SCOPE="--global"

say() {
  printf "\n==> %s\n" "$1"
}

if [[ ! -r /dev/tty ]]; then
  printf "social setup must be run from an interactive terminal.\n" >&2
  exit 1
fi

export PATH="$HOME/.bun/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"

if command -v npm >/dev/null 2>&1; then
  npm_bin="$(npm bin -g 2>/dev/null || true)"
  if [[ -n "$npm_bin" ]]; then
    export PATH="$npm_bin:$PATH"
  fi
fi

if command -v social >/dev/null 2>&1; then
  say "social CLI already installed"
elif command -v bun >/dev/null 2>&1; then
  say "Installing social with Bun"
  bun install -g "$CLI_PACKAGE"
elif command -v npm >/dev/null 2>&1; then
  say "Installing social with npm"
  npm install -g "$CLI_PACKAGE"
else
  printf "Install Bun or npm, then run this setup command again.\n" >&2
  exit 1
fi

if ! command -v social >/dev/null 2>&1; then
  printf "social installed, but the binary is not on PATH yet. Open a new terminal and run social account setup.\n" >&2
  exit 1
fi

say "Installing the social agent skill"
if command -v bunx >/dev/null 2>&1; then
  bunx skills add "$SKILL_PACKAGE" "$SKILL_SCOPE" < /dev/tty
elif command -v npx >/dev/null 2>&1; then
  npx skills add "$SKILL_PACKAGE" "$SKILL_SCOPE" < /dev/tty
else
  printf "Install Bun or npm to add the social skill, then run: npx skills add %s %s\n" "$SKILL_PACKAGE" "$SKILL_SCOPE" >&2
  exit 1
fi

say "Installing Social in detected MCP clients"
# social mcp install emits one fixed, shell-safe command for intentional word splitting.
$(social mcp install) < /dev/tty

say "Starting social account setup"
social account setup < /dev/tty
