#!/usr/bin/env bash
# One-command Odys developer setup for macOS. Idempotent — safe to re-run any time.
# Usage: curl -fsSL https://setup.odys.global | bash
#        bash bootstrap/install.sh --check-only    (doctor only, installs nothing)
set -euo pipefail

ORG="admin-odys-global"          # kept in sync with kit.config.json githubOrg
KIT_REPO="$ORG/deploy-manager"
MARKETPLACE="odys-kit"
PLUGIN="odys"
NODE_MAJOR="24"

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

run_doctor() {
  local dir=""
  dir="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null 2>&1 && pwd)" || dir=""
  if [ -n "$dir" ] && [ -f "$dir/doctor.sh" ]; then
    ODYS_ORG="$ORG" bash "$dir/doctor.sh"
  else
    curl -fsSL "https://setup.odys.global/doctor.sh" | ODYS_ORG="$ORG" bash
  fi
}

if [ "${1:-}" = "--check-only" ]; then
  run_doctor
  exit $?
fi

if [ "$(uname)" != "Darwin" ]; then
  echo "This script is for macOS. On Windows, use bootstrap/install.ps1." >&2
  exit 1
fi

say "Homebrew"
if ! command -v brew >/dev/null 2>&1; then
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi
eval "$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"

say "Core tools: git, gh, 1Password CLI"
brew list git >/dev/null 2>&1 || brew install git
brew list gh >/dev/null 2>&1 || brew install gh
brew list 1password-cli >/dev/null 2>&1 || brew install 1password-cli

say "Node $NODE_MAJOR"
if ! command -v node >/dev/null 2>&1 || [ "$(node -p 'process.versions.node.split(".")[0]')" != "$NODE_MAJOR" ]; then
  brew list "node@$NODE_MAJOR" >/dev/null 2>&1 || brew install "node@$NODE_MAJOR"
  NODE_PATH_LINE="export PATH=\"$(brew --prefix)/opt/node@$NODE_MAJOR/bin:\$PATH\""
  grep -qsF "node@$NODE_MAJOR/bin" "$HOME/.zprofile" 2>/dev/null || echo "$NODE_PATH_LINE" >> "$HOME/.zprofile"
  NODE_BIN_DIR="$(brew --prefix)/opt/node@$NODE_MAJOR/bin"
  export PATH="$NODE_BIN_DIR:$PATH"
fi

say "Claude Code"
if ! command -v claude >/dev/null 2>&1; then
  curl -fsSL https://claude.ai/install.sh | bash
  export PATH="$HOME/.local/bin:$PATH"
fi

say "GitHub sign-in"
if [ "${ODYS_SKIP_AUTH:-0}" = "1" ]; then
  echo "  skipped (ODYS_SKIP_AUTH=1)"
elif ! gh auth status >/dev/null 2>&1; then
  gh auth login --web --git-protocol https
else
  echo "  already signed in"
fi

say "Odys plugin"
if [ "${ODYS_SKIP_AUTH:-0}" = "1" ] && [ -f ".claude-plugin/marketplace.json" ]; then
  MARKETPLACE_SOURCE="$PWD"    # CI / local checkout: no GitHub auth available
else
  MARKETPLACE_SOURCE="$KIT_REPO"
fi
claude plugin marketplace list 2>/dev/null | grep -q "$MARKETPLACE" || claude plugin marketplace add "$MARKETPLACE_SOURCE"
claude plugin list 2>/dev/null | grep -q "$PLUGIN@$MARKETPLACE" || claude plugin install "$PLUGIN@$MARKETPLACE"

say "Final check"
run_doctor
