#!/usr/bin/env sh
# Solid# CLI bootstrap — macOS + Linux
#
# Usage:
#   curl -fsSL https://solidnumber.com/install.sh | sh
#
# What it does (in order):
#   1. Verify network + permissions
#   2. Install Node 20 LTS via fnm if `node` < 20 or missing
#   3. Upgrade the CLI through whichever manager already owns it
#      (npm / Homebrew / scoop), or npm install -g if nothing is installed
#   4. Run `solid auth login` to open the browser auth flow
#   5. Run `solid install` (Claude Code SessionStart hook) if Claude Code present
#   6. Run `solid completion install` for the active shell
#   7. Print "you're done" with three suggested next commands
#
# Re-runs are safe — every step is idempotent. Set SOLID_INSTALL_SKIP_LOGIN=1
# to skip the auth step (for CI / scripted installs that login with --token).
#
# Phase 3 magic-link auth: if SOLID_INSTALL_TOKEN is set in the environment,
# the bootstrap forwards it to `solid setup --install-token <token>` and the
# CLI exchanges it for a real session in one paste — no browser needed.
#
#   curl -fsSL https://solidnumber.com/install.sh | SOLID_INSTALL_TOKEN=ist_xxx sh
#
# Tokens come from /dashboard/install-command (logged-in user mints them
# fresh on every page load). 5-minute single-use TTL.

set -eu

# ─────────────────────────────────────────────────────────────────────────────
# Pretty output (colors when stdout is a TTY, plain otherwise)
# ─────────────────────────────────────────────────────────────────────────────
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  C_RESET="$(printf '\033[0m')"
  C_BOLD="$(printf '\033[1m')"
  C_GREEN="$(printf '\033[32m')"
  C_BLUE="$(printf '\033[34m')"
  C_YELLOW="$(printf '\033[33m')"
  C_RED="$(printf '\033[31m')"
  C_DIM="$(printf '\033[2m')"
else
  C_RESET=""; C_BOLD=""; C_GREEN=""; C_BLUE=""; C_YELLOW=""; C_RED=""; C_DIM=""
fi

step()    { printf "%s▸ %s%s\n"   "$C_BLUE"  "$1" "$C_RESET" >&2; }
ok()      { printf "%s✓ %s%s\n"   "$C_GREEN" "$1" "$C_RESET" >&2; }
warn()    { printf "%s! %s%s\n"   "$C_YELLOW" "$1" "$C_RESET" >&2; }
err()     { printf "%s✗ %s%s\n"   "$C_RED"   "$1" "$C_RESET" >&2; }
divider() { printf "%s%s%s\n"     "$C_DIM"   "────────────────────────────────────────" "$C_RESET" >&2; }

banner() {
  printf "\n"
  printf "%s%s  ╔══════════════════════════════════════════════════════╗%s\n" "$C_BOLD" "$C_GREEN" "$C_RESET"
  printf "%s%s  ║          Solid# CLI — one-command install           ║%s\n" "$C_BOLD" "$C_GREEN" "$C_RESET"
  printf "%s%s  ╚══════════════════════════════════════════════════════╝%s\n" "$C_BOLD" "$C_GREEN" "$C_RESET"
  printf "\n"
}

# ─────────────────────────────────────────────────────────────────────────────
# Detect platform
# ─────────────────────────────────────────────────────────────────────────────
detect_platform() {
  case "$(uname -s)" in
    Darwin)  echo "macos" ;;
    Linux)   echo "linux" ;;
    *)       echo "unknown" ;;
  esac
}

PLATFORM="$(detect_platform)"
if [ "$PLATFORM" = "unknown" ]; then
  err "Unsupported OS: $(uname -s)"
  err "This installer supports macOS and Linux. For Windows, run:"
  err "    iwr -useb https://solidnumber.com/install.ps1 | iex"
  exit 1
fi

# ─────────────────────────────────────────────────────────────────────────────
# Step 1 — verify Node ≥ 20
# ─────────────────────────────────────────────────────────────────────────────
ensure_node() {
  step "Checking Node.js..."

  if command -v node >/dev/null 2>&1; then
    NODE_VERSION="$(node -v | sed 's/^v//' | cut -d. -f1)"
    if [ "$NODE_VERSION" -ge 20 ] 2>/dev/null; then
      ok "Node $(node -v) detected (≥ 20 required)"
      return 0
    fi
    warn "Node $(node -v) is too old — Solid# CLI needs ≥ 20"
  else
    warn "Node.js not found"
  fi

  # Install via fnm — fast, no admin required, works on macOS + Linux
  step "Installing Node 20 LTS via fnm..."
  if ! command -v fnm >/dev/null 2>&1; then
    curl -fsSL https://fnm.vercel.app/install | bash -s -- --skip-shell >&2
    # fnm installs into ~/.local/share/fnm; surface it for the rest of THIS process
    export PATH="$HOME/.local/share/fnm:$PATH"
    eval "$(fnm env --use-on-cd 2>/dev/null || true)"
  fi

  fnm install 20 >&2
  fnm use 20 >&2
  fnm default 20 >&2

  if ! command -v node >/dev/null 2>&1; then
    err "Node install via fnm failed. Install Node 20 LTS manually from https://nodejs.org and re-run."
    exit 1
  fi
  ok "Node $(node -v) installed"
  warn "After install completes, add this to your shell rc to keep fnm on PATH:"
  warn "    eval \"\$(fnm env --use-on-cd)\""
}

# ─────────────────────────────────────────────────────────────────────────────
# Step 2 — install / upgrade the CLI
# ─────────────────────────────────────────────────────────────────────────────
# We publish through three channels (npm, Homebrew tap, scoop bucket) and for
# a long time this script ignored all of that and ran `npm i -g` regardless.
# If you had installed via `brew install solidnumber/tap/cli` and then ran the
# curl one-liner, you did not get an upgrade — you got a SECOND copy under
# npm, and which one actually ran came down to PATH order. The two drift
# apart, and the stale one wins the moment PATH changes (a different shell,
# cron, launchd, an editor terminal, or `nvm use` moving the npm copy out of
# the way). A silent downgrade to a months-old verb set is far worse than a
# "command not found", and for an AI agent driving this CLI it reads as a
# backend bug rather than an install problem.
#
# So: find every `solid` already on PATH, upgrade the one that is actually
# in charge using the manager that owns it, and say something loud if there
# is more than one.

# Print the path of every DISTINCT `solid` on PATH, one per line. Not just the
# first — finding the duplicates is the whole point.
#
# Deduplicated by resolved target, because a duplicated PATH entry is common
# and must not be reported as two installs. (The machine this was written on
# has its nvm bin directory listed twice, which made one binary look like two.)
find_all_solid() {
  _oldifs="$IFS"
  _seen=""
  IFS=:
  for _dir in $PATH; do
    [ -n "$_dir" ] || continue
    if [ -x "$_dir/solid" ]; then
      _key="$(resolve_solid "$_dir/solid")"
      case "
$_seen" in
        *"
$_key"*) ;;
        *) _seen="$_seen
$_key"; printf '%s\n' "$_dir/solid" ;;
      esac
    fi
  done
  IFS="$_oldifs"
}

# Absolute target of a possibly-symlinked binary. Used as the identity key so
# the same file reached by two PATH entries counts once.
resolve_solid() {
  _p="$1"
  if [ -L "$_p" ]; then
    _t="$(readlink "$_p")"
    case "$_t" in
      /*) _abs="$_t" ;;
      *)  _abs="$(dirname "$_p")/$_t" ;;
    esac
  else
    _abs="$_p"
  fi
  # Normalize through `cd`+`pwd -P` so that ../ segments collapse and symlinked
  # parents resolve. Without this, Homebrew's bin/solid -> ../Cellar/... yields
  # ".../bin/../Cellar/..." which does not string-match the same file reached
  # directly, and the two get counted as separate installs.
  _d="$(cd "$(dirname "$_abs")" 2>/dev/null && pwd -P)" || _d="$(dirname "$_abs")"
  printf '%s/%s\n' "$_d" "$(basename "$_abs")"
}

# Which package manager owns this binary? Homebrew links bin/solid into
# ../Cellar, so resolve one level of symlink before matching.
owner_of() {
  _p="$1"
  _real="$_p"
  if [ -L "$_p" ]; then
    _t="$(readlink "$_p")"
    case "$_t" in
      /*) _real="$_t" ;;
      *)  _real="$(dirname "$_p")/$_t" ;;
    esac
  fi
  case "$_real" in
    */Cellar/*)      printf 'brew\n' ;;
    */scoop/*)       printf 'scoop\n' ;;
    *)               printf 'npm\n' ;;
  esac
}

version_of() {
  "$1" --version 2>/dev/null | head -1 | tr -d '\r' || printf 'unknown\n'
}

upgrade_with() {
  case "$1" in
    brew)
      step "Existing Homebrew install detected — upgrading through brew"
      brew upgrade solidnumber/tap/cli >&2 || brew install solidnumber/tap/cli >&2
      ;;
    scoop)
      step "Existing scoop install detected — upgrading through scoop"
      scoop update solid >&2
      ;;
    *)
      npm i -g @solidnumber/cli@latest --no-fund --no-audit --loglevel=error >&2
      ;;
  esac
}

ensure_cli() {
  step "Installing @solidnumber/cli..."

  _found="$(find_all_solid || true)"
  _count="$(printf '%s\n' "$_found" | grep -c . || true)"
  [ -n "$_count" ] || _count=0

  # More than one `solid` on PATH: upgrading silently would leave the mess in
  # place and possibly make it worse. Name every copy, say which one wins, and
  # give the exact removal command for the others.
  if [ "$_count" -gt 1 ]; then
    warn "Found $_count \`solid\` binaries on PATH. Only the first one runs:"
    _first=1
    printf '%s\n' "$_found" | while IFS= read -r _p; do
      [ -n "$_p" ] || continue
      _o="$(owner_of "$_p")"
      _v="$(version_of "$_p")"
      if [ "$_first" = "1" ]; then
        printf "    %s%-42s %-9s %s  ← active%s\n" "$C_YELLOW" "$_p" "$_v" "$_o" "$C_RESET" >&2
        _first=0
      else
        printf "    %s%-42s %-9s %s  ← shadowed%s\n" "$C_DIM" "$_p" "$_v" "$_o" "$C_RESET" >&2
      fi
    done
    warn "Remove the ones you do not want, then re-run this installer:"
    warn "    brew uninstall solidnumber/tap/cli     # the Homebrew copy"
    warn "    npm uninstall -g @solidnumber/cli      # the npm copy"
    warn "    scoop uninstall solid                  # the scoop copy"
    warn "Continuing — upgrading the active copy only."
  fi

  # Upgrade through whichever manager owns the copy that actually runs, so we
  # never install a competing second copy. Nothing installed yet => npm.
  if [ "$_count" -ge 1 ]; then
    _active="$(printf '%s\n' "$_found" | head -1)"
    _method="$(owner_of "$_active")"
  else
    _method="npm"
  fi

  if upgrade_with "$_method"; then
    ok "CLI installed: $(solid --version 2>/dev/null || echo 'unknown version') (via $_method)"
  else
    if [ "$_method" = "npm" ]; then
      err "npm install failed. If you see EACCES errors, try:"
      err "    sudo npm i -g @solidnumber/cli@latest"
      err "Or configure npm to use a user-writable prefix:"
      err "    npm config set prefix ~/.npm-global"
      err "    export PATH=~/.npm-global/bin:\$PATH"
    else
      err "Upgrade via $_method failed. Re-run it by hand to see the error."
    fi
    exit 1
  fi
}

# ─────────────────────────────────────────────────────────────────────────────
# Step 3 — wire everything via `solid setup`
# ─────────────────────────────────────────────────────────────────────────────
# Phase 2 of SPRINT-CLI-ONE-COMMAND-ONBOARDING collapsed the chained
# auth/install/completion verbs into ONE `solid setup` umbrella. This
# bootstrap delegates to it instead of chaining the verbs ourselves —
# one place to evolve the wizard logic, one place to test it.
run_setup() {
  step "Running solid setup..."
  printf "%s%s    Auth + editor MCP + Claude hook + shell completion.%s\n" "$C_DIM" "" "$C_RESET" >&2

  # Build the setup args. SOLID_INSTALL_SKIP_LOGIN=1 inside the bootstrap
  # maps to --skip-auth on the setup wizard.
  setup_args=""
  if [ "${SOLID_INSTALL_SKIP_LOGIN:-0}" = "1" ]; then
    setup_args="--skip-auth"
  fi

  # Phase 3 magic-link auth: forward SOLID_INSTALL_TOKEN if set. The CLI
  # validates the prefix (must start with `ist_`) and exchanges it server-
  # side; bad/expired/replayed tokens get rejected with a useful error.
  if [ -n "${SOLID_INSTALL_TOKEN:-}" ]; then
    setup_args="$setup_args --install-token $SOLID_INSTALL_TOKEN"
    ok "Using install token from SOLID_INSTALL_TOKEN — skipping browser auth"
  fi

  # `--yes` accepts every non-destructive default. Stays interactive for
  # the auth browser flow because the underlying `solid auth login` always
  # opens a browser regardless. </dev/tty so the wizard can read prompts
  # even though we were piped in via curl|sh.
  if solid setup --yes $setup_args </dev/tty; then
    ok "Setup complete"
  else
    warn "Setup returned non-zero — run \`solid setup\` interactively to retry"
  fi
}

# ─────────────────────────────────────────────────────────────────────────────
# Final summary
# ─────────────────────────────────────────────────────────────────────────────
summary() {
  divider
  ok "Solid# CLI is installed and ready."
  printf "\n"
  printf "%sNext steps — pick one:%s\n" "$C_BOLD" "$C_RESET" >&2
  printf "  %ssolid clone plumber%s          # scaffold a business from a 54-industry template\n" "$C_GREEN" "$C_RESET" >&2
  printf "  %ssolid pull%s                   # pull an existing company's pages + KB locally\n" "$C_GREEN" "$C_RESET" >&2
  printf "  %ssolid demo create%s            # spin up a live demo company in 60 seconds\n" "$C_GREEN" "$C_RESET" >&2
  printf "  %ssolid ai%s                     # launch Claude Code / Cursor with this company's context\n" "$C_GREEN" "$C_RESET" >&2
  printf "\n"

  # ─────────────────────────────────────────────────────────────────────────
  # Connect an AI — and NEVER let this step be a silent no-op.
  #
  # This installer used to say it "wires Claude Code". What that meant was
  # `claude mcp add`, which needs `claude` on PATH; when it was absent the step
  # did nothing, said nothing, and the user typed `claude`, got
  # `command not found`, and stopped. The docs never said to install Claude
  # Code first, and Prerequisites correctly says Claude is not required — both
  # true, and together a wall.
  #
  # So: say which case they are in, and give the path that needs nothing.
  # ─────────────────────────────────────────────────────────────────────────
  printf "%sConnect your AI:%s\n" "$C_BOLD" "$C_RESET" >&2
  if command -v claude >/dev/null 2>&1; then
    printf "  Claude Code found. Wire it up:\n" >&2
    printf "  %sclaude mcp add --transport http solidnumber https://api.solidnumber.com/mcp/connector%s\n" "$C_GREEN" "$C_RESET" >&2
  else
    printf "  %sClaude Code is NOT installed — that is fine, it is not required.%s\n" "$C_YELLOW" "$C_RESET" >&2
    printf "  Using ChatGPT, Claude in the browser, Cursor, Grok or anything else?\n" >&2
  fi
  printf "  %ssolid mcp connect%s             # pick your AI, get the exact steps\n" "$C_GREEN" "$C_RESET" >&2
  printf "\n"
  printf "  Any tool that speaks MCP needs only this URL — no CLI, no install:\n" >&2
  printf "  %shttps://api.solidnumber.com/mcp/connector%s\n" "$C_BLUE" "$C_RESET" >&2
  printf "\n"
  printf "Docs: %shttps://solidnumber.com/docs/cli%s\n" "$C_BLUE" "$C_RESET" >&2
  printf "\n"
}

# ─────────────────────────────────────────────────────────────────────────────
# Run
# ─────────────────────────────────────────────────────────────────────────────
main() {
  banner
  ensure_node
  ensure_cli
  run_setup
  summary
}

main "$@"
