#!/bin/sh
# ============================================================
# Composure — Installer (macOS / Linux)
# ============================================================
# Usage:   curl -fsSL https://composure-pro.com/install.sh | sh
# Options: curl -fsSL https://composure-pro.com/install.sh | sh -s -- --payload-version 1.2.3 --non-interactive
#          (or set COMPOSURE_PAYLOAD_VERSION / COMPOSURE_NON_INTERACTIVE=1)
#
# What it does:
#   1. Checks prerequisites (Node.js 22.5+) and explains the fix if missing
#   2. Delegates the install to create-composure (the engine), which
#      detects your AI coding tools, installs Claude Code if missing,
#      registers the local Composure marketplace, installs the plugin
#      suite, and links the CLI commands
#   3. Adds ~/.composure/bin to PATH
#   4. Tells you the next step: sign in
#
# Works with: Claude Code, Cursor, Windsurf, Gemini CLI, Codex CLI,
#             Cline, Roo Code, Aider, and Git.
#
# Safe to read first: curl -fsSL https://composure-pro.com/install.sh
# Never uses sudo. Never reads, prints, or logs credentials.
# POSIX sh only — no bashisms.
# ============================================================

set -eu

# ── Output ────────────────────────────────────────────────────

if [ -t 1 ]; then
  ESC=$(printf '\033')
  RED="${ESC}[0;31m"; GREEN="${ESC}[0;32m"; YELLOW="${ESC}[0;33m"
  BLUE="${ESC}[0;34m"; BOLD="${ESC}[1m"; NC="${ESC}[0m"
else
  RED=''; GREEN=''; YELLOW=''; BLUE=''; BOLD=''; NC=''
fi

info()    { printf '%sinfo%s  %s\n' "$BLUE" "$NC" "$1"; }
success() { printf '%s  ok%s  %s\n' "$GREEN" "$NC" "$1"; }
warn()    { printf '%swarn%s  %s\n' "$YELLOW" "$NC" "$1"; }
fail()    { printf '%sfail%s  %s\n' "$RED" "$NC" "$1" >&2; exit 1; }

usage() {
  printf 'Usage: curl -fsSL https://composure-pro.com/install.sh | sh -s -- [options]\n\n'
  printf 'Options:\n'
  printf '  --payload-version <v>   Install a specific Composure release (default: latest)\n'
  printf '  --non-interactive       Never prompt (implied when piped)\n'
  printf '  -h, --help              Show this help\n'
}

# ── Arguments (env vars first, flags override) ────────────────

PAYLOAD_VERSION="${COMPOSURE_PAYLOAD_VERSION:-}"
NON_INTERACTIVE=0
case "${COMPOSURE_NON_INTERACTIVE:-}" in 1|true|yes) NON_INTERACTIVE=1 ;; esac

while [ $# -gt 0 ]; do
  case "$1" in
    --payload-version)
      [ $# -ge 2 ] || fail "--payload-version needs a value, e.g. --payload-version 1.2.3"
      PAYLOAD_VERSION="$2"; shift 2 ;;
    --payload-version=*) PAYLOAD_VERSION="${1#--payload-version=}"; shift ;;
    --non-interactive)   NON_INTERACTIVE=1; shift ;;
    -h|--help)           usage; exit 0 ;;
    *) usage >&2; fail "Unknown option: $1" ;;
  esac
done

case "$PAYLOAD_VERSION" in
  *[!0-9A-Za-z._-]*) fail "Invalid --payload-version (letters, digits, '.', '_', '-' only)." ;;
esac

# Piped install (curl | sh): stdin is the script itself. Never let a child
# read it, or its prompts would consume the remaining script bytes.
if [ ! -t 0 ]; then NON_INTERACTIVE=1; fi

# ── Platform ──────────────────────────────────────────────────

OS_NAME=$(uname -s 2>/dev/null || echo unknown)
case "$OS_NAME" in
  MINGW*|MSYS*|CYGWIN*)
    warn "Windows detected. Use the PowerShell installer instead:"
    printf '\n  %sirm https://composure-pro.com/install.ps1 | iex%s\n\n' "$BOLD" "$NC"
    exit 0
    ;;
  Darwin) PLATFORM=mac ;;
  *)      PLATFORM=linux ;;
esac

# ── Header ────────────────────────────────────────────────────

printf '\n%sComposure Installer%s\n' "$BOLD" "$NC"
printf 'Universal code quality enforcement for AI coding tools\n\n'

if [ "$(id -u 2>/dev/null || echo 1)" = "0" ]; then
  warn "Running as root. Composure installs into your home directory and never needs sudo; run it as your normal user."
fi

# ── Node.js fix commands (per OS, no sudo) ────────────────────

node_fix() {
  printf '\n  Install or upgrade Node.js 22.5+ (no sudo needed), then run this installer again:\n\n'
  if [ "$PLATFORM" = mac ]; then
    printf '    Homebrew:  brew install node@22 && brew link --overwrite node@22\n'
  fi
  printf '    fnm:       curl -fsSL https://fnm.vercel.app/install | bash\n'
  printf '               (open a new terminal)  fnm install 22 && fnm default 22\n'
  printf '    Download:  https://nodejs.org/en/download\n\n'
}

# ── Check: Node.js ────────────────────────────────────────────

info "Checking Node.js..."
if ! command -v node >/dev/null 2>&1; then
  printf '%sfail%s  Node.js not found. Composure needs Node.js 22.5+.\n' "$RED" "$NC" >&2
  node_fix >&2
  exit 1
fi

NODE_VERSION=$(node -e "console.log(process.versions.node)" 2>/dev/null || true)
[ -n "$NODE_VERSION" ] || { node_fix >&2; fail "Could not read the Node.js version. Reinstall Node.js 22.5+."; }
NODE_MAJOR=${NODE_VERSION%%.*}
NODE_REST=${NODE_VERSION#*.}
NODE_MINOR=${NODE_REST%%.*}

if [ "$NODE_MAJOR" -lt 22 ] || { [ "$NODE_MAJOR" -eq 22 ] && [ "$NODE_MINOR" -lt 5 ]; }; then
  printf '%sfail%s  Node.js %s found, but 22.5+ is required for the code graph.\n' "$RED" "$NC" "$NODE_VERSION" >&2
  node_fix >&2
  exit 1
fi
success "Node.js $NODE_VERSION"

# ── Check: package runner ─────────────────────────────────────

if command -v pnpm >/dev/null 2>&1; then
  RUNNER=pnpm
elif command -v npx >/dev/null 2>&1; then
  RUNNER=npx
else
  fail "Neither pnpm nor npx found. npx ships with Node.js; reinstall Node.js 22.5+ (https://nodejs.org/en/download)."
fi

# ── Check: network ────────────────────────────────────────────

if command -v curl >/dev/null 2>&1; then
  info "Checking network..."
  if ! curl -fsS --max-time 15 -o /dev/null "https://registry.npmjs.org/create-composure" 2>/dev/null; then
    fail "Cannot reach registry.npmjs.org. Check your internet connection, VPN, or proxy settings (HTTPS_PROXY), then run this installer again."
  fi
  success "Network reachable"
fi

# ── Install Composure (delegates to create-composure) ─────────

printf '\n'
info "Installing Composure..."

set -- "create-composure@latest"
[ -n "$PAYLOAD_VERSION" ] && set -- "$@" --payload-version "$PAYLOAD_VERSION"
[ "$NON_INTERACTIVE" -eq 1 ] && set -- "$@" --non-interactive

run_engine() {
  if [ "$NON_INTERACTIVE" -eq 1 ]; then
    if [ "$RUNNER" = pnpm ]; then pnpm dlx "$@" < /dev/null; else npx -y "$@" < /dev/null; fi
  else
    if [ "$RUNNER" = pnpm ]; then pnpm dlx "$@"; else npx -y "$@"; fi
  fi
}

if ! run_engine "$@"; then
  fail "Composure install failed. See the output above. If it was a network error, check your connection and run the installer again (it is safe to re-run)."
fi

# ── Add to PATH ───────────────────────────────────────────────

BIN_DIR="$HOME/.composure/bin"
ADDED_PATH=0
# shellcheck disable=SC2016 # literal $HOME is written into the rc file on purpose
PATH_LINE='export PATH="$HOME/.composure/bin:$PATH"'

for RC_FILE in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.profile"; do
  if [ -f "$RC_FILE" ] && ! grep -q '.composure/bin' "$RC_FILE" 2>/dev/null; then
    printf '\n# Composure CLI\n%s\n' "$PATH_LINE" >> "$RC_FILE"
    ADDED_PATH=1
  fi
done

if [ "$ADDED_PATH" -eq 1 ]; then
  success "Added ~/.composure/bin to PATH (restart your shell to apply)"
else
  success "PATH already configured"
fi

PATH="$BIN_DIR:$PATH"
export PATH

# ── Done ──────────────────────────────────────────────────────

printf '\n%s%sComposure installed.%s\n\n' "$GREEN" "$BOLD" "$NC"
printf 'Next steps:\n'
printf '  %s1.%s Sign in:  %scomposure-auth login%s   (opens your browser; open a new terminal first if the command is not found — on installs made before Nov 2026, run composure-auth.mjs login)\n' "$BOLD" "$NC" "$BOLD" "$NC"
printf '  %s2.%s Restart Claude Code (Ctrl+C then %sclaude%s)\n' "$BOLD" "$NC" "$BOLD" "$NC"
printf '  %s3.%s Run %s/composure:initialize%s in your project\n' "$BOLD" "$NC" "$BOLD" "$NC"
printf '\nCheck your plan any time with %scomposure-auth status%s.\n' "$BOLD" "$NC"
printf 'Docs: %shttps://composure-pro.com%s\n\n' "$BLUE" "$NC"
