#!/usr/bin/env bash
# =============================================================================
#  protospec — one-shot setup helper (bootstrap.sh)
# =============================================================================
#
#  WHAT THIS IS
#  ------------
#  A friendly, self-contained setup script for the "protospec" template project.
#  It is written for product managers on a Mac who may have NONE of the
#  developer tools installed yet. It checks for each prerequisite, installs only
#  what is missing, and explains every step in plain language before it does
#  anything that changes your computer or pops up a dialog.
#
#  HOW TO USE IT
#  ------------
#  On a brand-new Mac, open Terminal (Applications > Utilities > Terminal) and paste:
#
#      /bin/bash -c "$(curl -fsSL https://protospec.wis-build.io/install.sh)"
#
#  (That public copy is published from the template's bootstrap.sh by
#  scripts/publish-installer.sh.) Inside a project folder you can also run ./bootstrap.sh.
#
#  It is SAFE TO RUN AGAIN. Anything already installed is detected and skipped,
#  so re-running just fills in whatever is still missing.
#
#  WHAT IT SETS UP
#  ------------
#      1. Xcode Command Line Tools (Apple's basic developer toolkit)
#      2. Homebrew          (the macOS software installer used below)
#      3. git               (version control — tracks your work)
#      4. Node.js + npm     (runs the prototype)
#      5. GitHub access     (GitHub CLI login — creates projects, saves & shares work)
#      6. git identity      (your name + email on saved work)
#      7. Claude Code       (the AI agent you work with)
#      8. protospec command (`protospec new <name>` creates a project + its GitHub repo)
#      9. Your project      (create a new one or open an existing one; or, when run
#                            inside a project folder, `npm install` there)
#
#  MAINTAINER NOTES (for the AI-infra engineer)
#  ------------
#  - Deliberately does NOT use `set -e`. We want to inspect each prerequisite,
#    report pass/fail, install only the gaps, and keep going. A hard failure in
#    one optional step should not abort the whole run. Individual steps guard
#    their own critical failures and set FATAL where appropriate.
#  - Every step is idempotent: it checks current state first and no-ops if the
#    thing is already there.
#  - Handles both Apple Silicon (/opt/homebrew) and Intel (/usr/local) Homebrew
#    prefixes.
#  - Interactive prompts are TTY-guarded so the script degrades gracefully when
#    piped (e.g. `curl ... | bash`) instead of hanging on `read`.
# =============================================================================


# -----------------------------------------------------------------------------
#  Output helpers — colors, emoji, and consistent formatting.
#  We keep color usage light and fall back to plain text when the output is not
#  a terminal (so logs / pipes stay readable).
# -----------------------------------------------------------------------------
if [ -t 1 ]; then
  BOLD="$(printf '\033[1m')"
  DIM="$(printf '\033[2m')"
  RED="$(printf '\033[31m')"
  GREEN="$(printf '\033[32m')"
  YELLOW="$(printf '\033[33m')"
  BLUE="$(printf '\033[34m')"
  RESET="$(printf '\033[0m')"
else
  BOLD="" ; DIM="" ; RED="" ; GREEN="" ; YELLOW="" ; BLUE="" ; RESET=""
fi

# A big section header, e.g. "STEP 2 of 9".
section() {
  printf '\n%s%s──────────────────────────────────────────────────────────%s\n' "$BOLD" "$BLUE" "$RESET"
  printf '%s%s%s\n' "$BOLD" "$1" "$RESET"
  printf '%s%s──────────────────────────────────────────────────────────%s\n' "$BOLD" "$BLUE" "$RESET"
}

ok()      { printf '%s✓%s %s\n' "$GREEN" "$RESET" "$1"; }        # success / already present
missing() { printf '%s✗%s %s\n' "$RED"   "$RESET" "$1"; }        # not found, will install
info()    { printf '%s•%s %s\n' "$BLUE"  "$RESET" "$1"; }        # neutral note
warn()    { printf '%s⚠%s  %s\n' "$YELLOW" "$RESET" "$1"; }      # heads-up
# "I'm about to change your machine" line — always shown before mutating actions.
plan()    { printf '\n%s→ About to:%s %s\n' "$YELLOW" "$RESET" "$1"; }

# -----------------------------------------------------------------------------
#  Bookkeeping: track what we installed vs. what was already there, so we can
#  print a clean summary at the end.
# -----------------------------------------------------------------------------
INSTALLED=()          # things this run installed
ALREADY=()            # things already present
SKIPPED=()            # things we could not / chose not to do (with reason)
FATAL=0               # set to 1 by a step that can't sensibly continue

mark_installed() { INSTALLED+=("$1"); }
mark_already()   { ALREADY+=("$1"); }
mark_skipped()   { SKIPPED+=("$1"); }

# -----------------------------------------------------------------------------
#  TTY-safe prompting. If there is no interactive terminal on stdin (e.g. the
#  script was piped), we CANNOT ask questions — so we skip and tell the user
#  exactly what to do instead of hanging forever on `read`.
# -----------------------------------------------------------------------------
have_tty() { [ -t 0 ]; }

# ask VAR "Prompt text" "default"
# Reads a line into the named variable. Returns 1 if no TTY (caller decides).
ask() {
  local __var="$1" __prompt="$2" __default="${3:-}" __reply
  if ! have_tty; then
    return 1
  fi
  if [ -n "$__default" ]; then
    printf '%s %s[%s]%s: ' "$__prompt" "$DIM" "$__default" "$RESET"
  else
    printf '%s: ' "$__prompt"
  fi
  read -r __reply
  [ -z "$__reply" ] && __reply="$__default"
  printf -v "$__var" '%s' "$__reply"
  return 0
}

# ask_yes_no "Question" default(y/n) -> returns 0 for yes, 1 for no
ask_yes_no() {
  local __prompt="$1" __default="${2:-y}" __reply
  if ! have_tty; then
    # Non-interactive: assume the default so the run can proceed unattended.
    [ "$__default" = "y" ] && return 0 || return 1
  fi
  local hint="[Y/n]"; [ "$__default" = "n" ] && hint="[y/N]"
  printf '%s %s ' "$__prompt" "$hint"
  read -r __reply
  __reply="${__reply:-$__default}"
  case "$__reply" in
    [Yy]*) return 0 ;;
    *)     return 1 ;;
  esac
}

# Pause until the user presses Enter (used when they must do something in the
# browser). No-op when non-interactive.
press_enter() {
  local __prompt="${1:-Press Enter to continue}"
  if ! have_tty; then
    return 0
  fi
  printf '\n%s%s%s ' "$DIM" "$__prompt..." "$RESET"
  read -r _ || true
}


# -----------------------------------------------------------------------------
#  Resolve the directory this script lives in, robustly, so `npm install` runs
#  in the project root no matter where the user invoked the script from.
#  (Follows a single symlink level; good enough for our use.)
# -----------------------------------------------------------------------------
resolve_script_dir() {
  local src="${BASH_SOURCE[0]}"
  while [ -h "$src" ]; do
    local dir
    dir="$(cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd)"
    src="$(readlink "$src")"
    [[ "$src" != /* ]] && src="$dir/$src"
  done
  cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd
}
SCRIPT_DIR="$(resolve_script_dir)"


# -----------------------------------------------------------------------------
#  Homebrew PATH helper. Homebrew installs to different prefixes depending on
#  the chip:
#     - Apple Silicon (M1/M2/M3...) -> /opt/homebrew
#     - Intel                       -> /usr/local
#  This makes `brew` usable in THIS shell session even if the profile hasn't
#  been re-sourced yet.
# -----------------------------------------------------------------------------
BREW_PREFIX=""
load_brew_into_path() {
  if command -v brew >/dev/null 2>&1; then
    BREW_PREFIX="$(brew --prefix 2>/dev/null)"
    return 0
  fi
  local candidate
  for candidate in /opt/homebrew/bin/brew /usr/local/bin/brew; do
    if [ -x "$candidate" ]; then
      eval "$("$candidate" shellenv)"
      BREW_PREFIX="$("$candidate" --prefix 2>/dev/null)"
      return 0
    fi
  done
  return 1
}


# =============================================================================
#  PRE-FLIGHT: confirm we are on macOS.
# =============================================================================
preflight_os_check() {
  local os
  os="$(uname -s)"
  if [ "$os" != "Darwin" ]; then
    printf '\n%s%sThis setup helper is built for macOS.%s\n' "$BOLD" "$YELLOW" "$RESET"
    if [ "$os" = "Linux" ]; then
      cat <<'EOF'

You appear to be on Linux. This script targets Macs, so it can't run as-is,
but the pieces you need are the same. On most Linux systems you would:

  • Install git and Node.js with your package manager, e.g.
        sudo apt install git nodejs npm      (Debian/Ubuntu)
  • Set up GitHub access with the GitHub CLI (`gh auth login`) or an SSH key
  • Then run `npm install` in the project folder

If you're actually on a Mac and seeing this, something is unusual — please
reach out for help.
EOF
    else
      printf '\nDetected operating system: %s. Please run this on a Mac.\n' "$os"
    fi
    exit 1
  fi
}


# =============================================================================
#  STEP 1 — Xcode Command Line Tools
#  Apple's base developer toolkit. Homebrew and git need it. Installing it pops
#  a SYSTEM DIALOG the user must click through, so we explain that and then poll
#  until it finishes.
# =============================================================================
step_xcode_clt() {
  section "STEP 1 of 9 — Xcode Command Line Tools"
  info "These are Apple's basic developer tools. Other tools below depend on them."

  if xcode-select -p >/dev/null 2>&1; then
    ok "Already installed ($(xcode-select -p))"
    mark_already "Xcode Command Line Tools"
    return 0
  fi

  missing "Not installed yet."

  if ! have_tty; then
    warn "Can't run the interactive installer right now (no terminal to watch)."
    warn "Please run this script directly in Terminal, or run:  xcode-select --install"
    mark_skipped "Xcode Command Line Tools (needs interactive terminal)"
    FATAL=1
    return 1
  fi

  plan "ask macOS to install the Command Line Tools. A small Apple dialog will pop up."
  printf '   When it appears, click the %sInstall%s button and agree to the license.\n' "$BOLD" "$RESET"
  printf '   (The download can take several minutes depending on your connection.)\n'

  xcode-select --install >/dev/null 2>&1

  # Poll until the tools appear. We wait patiently; the user drives the dialog.
  printf '\n   Waiting for the installation to finish'
  local waited=0
  while ! xcode-select -p >/dev/null 2>&1; do
    printf '.'
    sleep 5
    waited=$((waited + 5))
    # Gentle reminder every ~2 minutes in case they missed the dialog.
    if [ $((waited % 120)) -eq 0 ]; then
      printf '\n   %sStill waiting — make sure you clicked "Install" in the Apple dialog.%s\n   ' "$DIM" "$RESET"
    fi
  done
  printf '\n'

  if xcode-select -p >/dev/null 2>&1; then
    ok "Installed successfully."
    mark_installed "Xcode Command Line Tools"
  else
    missing "Still not detected — please finish the Apple dialog and re-run this script."
    mark_skipped "Xcode Command Line Tools (installation not completed)"
    FATAL=1
  fi
}


# =============================================================================
#  STEP 2 — Homebrew
#  The package manager we use to install git, node, and gh. After installing,
#  we make brew available in THIS session and persist it to ~/.zprofile.
# =============================================================================
ensure_brew_in_profile() {
  # Append the correct `eval "$(brew shellenv)"` to ~/.zprofile if not present,
  # so `brew` works in every future Terminal window.
  local brew_bin="$BREW_PREFIX/bin/brew"
  [ -x "$brew_bin" ] || return 1
  local line="eval \"\$($brew_bin shellenv)\""
  local profile="$HOME/.zprofile"
  touch "$profile"
  if grep -qF "$brew_bin shellenv" "$profile" 2>/dev/null; then
    info "Homebrew is already wired into your shell profile."
  else
    printf '\n# Added by protospec bootstrap.sh — makes Homebrew available in new terminals\n%s\n' "$line" >> "$profile"
    ok "Added Homebrew to your shell profile (~/.zprofile)."
  fi
}

step_homebrew() {
  section "STEP 2 of 9 — Homebrew"
  info "Homebrew is the tool that installs the other software below."

  if load_brew_into_path; then
    ok "Already installed ($(brew --version 2>/dev/null | head -n1))"
    mark_already "Homebrew"
    ensure_brew_in_profile
    return 0
  fi

  missing "Not installed yet."

  if ! have_tty; then
    warn "Homebrew's installer needs an interactive terminal (it may ask for your password)."
    warn "Please run this script directly in Terminal."
    mark_skipped "Homebrew (needs interactive terminal)"
    FATAL=1
    return 1
  fi

  plan "download and run the official Homebrew installer from brew.sh."
  printf '   It may ask for your Mac password (to authorize the install). That is expected.\n'

  # NONINTERACTIVE=1 keeps the installer from prompting for confirmation, but it
  # may still request your macOS password via sudo.
  NONINTERACTIVE=1 /bin/bash -c \
    "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  if load_brew_into_path; then
    ok "Homebrew installed ($(brew --version 2>/dev/null | head -n1))"
    mark_installed "Homebrew"
    ensure_brew_in_profile
  else
    missing "Homebrew install did not complete. Please re-run this script."
    mark_skipped "Homebrew (installation failed)"
    FATAL=1
  fi
}


# -----------------------------------------------------------------------------
#  Generic "install a brew formula if the command is missing" helper.
#  Usage: brew_ensure <command-name> <formula-name> <friendly-label>
# -----------------------------------------------------------------------------
brew_ensure() {
  local cmd="$1" formula="$2" label="$3"
  if command -v "$cmd" >/dev/null 2>&1; then
    ok "$label already installed ($("$cmd" --version 2>/dev/null | head -n1))"
    mark_already "$label"
    return 0
  fi
  missing "$label not installed yet."
  if ! command -v brew >/dev/null 2>&1; then
    warn "Homebrew isn't available, so $label can't be installed automatically."
    mark_skipped "$label (Homebrew missing)"
    return 1
  fi
  plan "install $label with Homebrew (brew install $formula)."
  if brew install "$formula"; then
    ok "$label installed."
    mark_installed "$label"
  else
    missing "$label failed to install — see the messages above."
    mark_skipped "$label (brew install failed)"
    return 1
  fi
}


# =============================================================================
#  STEP 3 — git
# =============================================================================
step_git() {
  section "STEP 3 of 9 — git"
  info "git keeps a history of your work so nothing gets lost."
  brew_ensure git git "git"
}


# =============================================================================
#  STEP 4 — Node.js + npm
#  `node` runs the prototype; `npm` installs its building blocks. Homebrew's
#  `node` formula bundles both.
# =============================================================================
step_node() {
  section "STEP 4 of 9 — Node.js + npm"
  info "Node.js runs the prototype in your browser. npm comes bundled with it."

  local have_node=0 have_npm=0
  command -v node >/dev/null 2>&1 && have_node=1
  command -v npm  >/dev/null 2>&1 && have_npm=1

  if [ "$have_node" -eq 1 ] && [ "$have_npm" -eq 1 ]; then
    ok "Node.js already installed ($(node --version 2>/dev/null))"
    ok "npm already installed (v$(npm --version 2>/dev/null))"
    mark_already "Node.js + npm"
    return 0
  fi

  missing "Node.js / npm not fully installed yet."
  brew_ensure node node "Node.js + npm"

  # Re-verify both are now callable and report versions.
  if command -v node >/dev/null 2>&1 && command -v npm >/dev/null 2>&1; then
    ok "Verified Node.js $(node --version 2>/dev/null) and npm v$(npm --version 2>/dev/null)"
  else
    warn "Node.js or npm still not detected. You may need to open a new Terminal window."
  fi
}


# =============================================================================
#  STEP 5 — GitHub access
#  Two supported paths:
#    (A) GitHub CLI (`gh`) — the friendly default. `gh auth login` walks the
#        user through logging their computer into GitHub and sets up
#        credentials/keys for them.
#    (B) SSH key — for users who prefer it, or when gh can't be installed.
#        We generate an ed25519 key, load it into the macOS keychain, copy the
#        PUBLIC key to the clipboard, and walk them through adding it on GitHub.
# =============================================================================

# ---- Path B: SSH key setup --------------------------------------------------
setup_ssh_key() {
  info "Setting up an SSH key. Think of this as a private key + a public 'lock'."
  info "You paste the public 'lock' into GitHub; the private key stays on your Mac."

  local key="$HOME/.ssh/id_ed25519"
  local pub="$key.pub"

  # We need an email to label the key. Reuse git email if set, else ask.
  local email
  email="$(git config --global user.email 2>/dev/null)"
  if [ -z "$email" ]; then
    if ! ask email "   What email should label this key? (your GitHub email)"; then
      warn "No email available and can't prompt — skipping SSH setup."
      mark_skipped "GitHub SSH key (no email / non-interactive)"
      return 1
    fi
  fi

  mkdir -p "$HOME/.ssh"
  chmod 700 "$HOME/.ssh"

  if [ -f "$key" ]; then
    ok "You already have an SSH key ($key) — keeping it."
    mark_already "GitHub SSH key"
  else
    plan "create a new SSH key on your Mac (no password needed for this key)."
    # -N "" = no passphrase (simpler for non-technical users; keychain guards it).
    if ssh-keygen -t ed25519 -C "$email" -f "$key" -N "" >/dev/null 2>&1; then
      ok "Created a new SSH key."
      mark_installed "GitHub SSH key"
    else
      missing "Could not create an SSH key."
      mark_skipped "GitHub SSH key (ssh-keygen failed)"
      return 1
    fi
  fi

  # Start the ssh-agent and add the key to the macOS keychain so you don't have
  # to re-enter anything later.
  eval "$(ssh-agent -s)" >/dev/null 2>&1
  if ssh-add --apple-use-keychain "$key" >/dev/null 2>&1; then
    ok "Loaded the key into your Mac's secure keychain."
  else
    # Older macOS used -K instead of --apple-use-keychain.
    ssh-add -K "$key" >/dev/null 2>&1 || ssh-add "$key" >/dev/null 2>&1 || true
  fi

  # Copy the PUBLIC key to the clipboard so the user just has to paste it.
  if [ -f "$pub" ] && command -v pbcopy >/dev/null 2>&1; then
    pbcopy < "$pub"
    ok "Your PUBLIC key is now copied to your clipboard, ready to paste."
  else
    warn "Couldn't copy automatically. Here is your public key — copy the whole line:"
    printf '\n%s\n\n' "$(cat "$pub" 2>/dev/null)"
  fi

  # Walk them through adding it on GitHub.
  cat <<EOF

   ${BOLD}Now add the key to GitHub:${RESET}
     1. Open this page in your browser:
          ${BLUE}https://github.com/settings/ssh/new${RESET}
     2. In the "Title" box, type something like: My Mac
     3. Click in the big "Key" box and paste (Command-V) — it's already copied.
     4. Click the green "Add SSH key" button.
EOF

  press_enter "When you've added the key on GitHub, press Enter here"

  # Verify. GitHub's SSH check greets you and exits with code 1 — that is NORMAL
  # and actually means success. We look for the success greeting in the output.
  info "Checking the connection to GitHub..."
  local out
  # -o StrictHostKeyChecking=accept-new auto-accepts GitHub's fingerprint the
  # first time instead of prompting (safe for github.com).
  out="$(ssh -o StrictHostKeyChecking=accept-new -T git@github.com 2>&1)"
  if printf '%s' "$out" | grep -qi "successfully authenticated"; then
    ok "Connected to GitHub over SSH. You're all set."
    return 0
  else
    warn "Couldn't confirm the connection yet. GitHub said:"
    printf '   %s\n' "$out"
    warn "If you just added the key, give it a moment and re-run this script."
    return 1
  fi
}

# ---- Path A: GitHub CLI -----------------------------------------------------
setup_gh_cli() {
  # Ensure gh is installed.
  if ! command -v gh >/dev/null 2>&1; then
    brew_ensure gh gh "GitHub CLI" || return 1
  else
    ok "GitHub CLI already installed ($(gh --version 2>/dev/null | head -n1))"
    mark_already "GitHub CLI"
  fi

  # Already logged in?
  if gh auth status >/dev/null 2>&1; then
    ok "You're already logged into GitHub."
    mark_already "GitHub login"
    return 0
  fi

  missing "Not logged into GitHub yet."
  if ! have_tty; then
    warn "Logging in needs an interactive terminal. Please run this script directly,"
    warn "then run:  gh auth login"
    mark_skipped "GitHub login (needs interactive terminal)"
    return 1
  fi

  plan "log your computer into GitHub so you can save and share your work."
  info "The GitHub CLI will ask you a few short questions and open your browser."
  info "Tip: choose 'GitHub.com', then 'HTTPS' or 'SSH', then 'Login with a web browser'."
  printf '\n'

  if gh auth login; then
    ok "Logged into GitHub."
    mark_installed "GitHub login"
    # Let gh manage git's credential helper so pushes/pulls just work.
    gh auth setup-git >/dev/null 2>&1 && info "Configured git to use your GitHub login."
    return 0
  else
    missing "GitHub login didn't complete."
    mark_skipped "GitHub login (gh auth login did not finish)"
    return 1
  fi
}

step_github_access() {
  section "STEP 5 of 9 — GitHub access"
  info "This logs your Mac into GitHub so you can create projects, save your work, and share links."

  # The GitHub CLI login is required: `protospec new` uses it to create each project's repo.
  if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
    ok "You're already logged into GitHub via the GitHub CLI."
    mark_already "GitHub access"
    return 0
  fi

  if setup_gh_cli; then
    return 0
  fi

  # The CLI couldn't be set up. An SSH key at least lets them open existing projects.
  warn "Creating new projects needs the GitHub CLI login — re-run this script to finish it."
  if have_tty && ask_yes_no "   Meanwhile, set up an SSH key so you can open existing projects?" "n"; then
    setup_ssh_key
  else
    mark_skipped "GitHub access (not completed)"
  fi
}


# =============================================================================
#  STEP 6 — git identity
#  Every saved change is stamped with a name + email. Set them if missing.
# =============================================================================
step_git_identity() {
  section "STEP 6 of 9 — Your name & email for saved work"
  info "git stamps each save with your name and email. Let's make sure they're set."

  if ! command -v git >/dev/null 2>&1; then
    warn "git isn't installed, so we can't set this yet."
    mark_skipped "git identity (git missing)"
    return 1
  fi

  local cur_name cur_email
  cur_name="$(git config --global user.name 2>/dev/null)"
  cur_email="$(git config --global user.email 2>/dev/null)"

  if [ -n "$cur_name" ] && [ -n "$cur_email" ]; then
    ok "Already set: $cur_name <$cur_email>"
    mark_already "git identity"
    return 0
  fi

  if ! have_tty; then
    warn "Name/email not set and can't prompt right now. Set them later with:"
    printf '     git config --global user.name  "Your Name"\n'
    printf '     git config --global user.email "you@example.com"\n'
    mark_skipped "git identity (non-interactive)"
    return 1
  fi

  local name email
  if [ -z "$cur_name" ]; then
    ask name "   Your full name (e.g. Jane Smith)" "" || true
    [ -n "$name" ] && git config --global user.name "$name" && ok "Saved your name."
  fi
  if [ -z "$cur_email" ]; then
    ask email "   Your email (your GitHub email is ideal)" "" || true
    [ -n "$email" ] && git config --global user.email "$email" && ok "Saved your email."
  fi
  mark_installed "git identity"
}


# =============================================================================
#  STEP 7 — Claude Code
#  The AI agent the PM works with. Anthropic's official installer puts the
#  `claude` command in ~/.local/bin.
# =============================================================================
step_claude_code() {
  section "STEP 7 of 9 — Claude Code"
  info "Claude Code is the AI agent you work with: it does the mechanics while you make the product decisions."

  if command -v claude >/dev/null 2>&1; then
    ok "Claude Code already installed ($(claude --version 2>/dev/null | head -n1))"
    mark_already "Claude Code"
    return 0
  fi

  missing "Claude Code isn't installed yet."
  plan "install Claude Code using Anthropic's official installer."
  if curl -fsSL https://claude.ai/install.sh | bash; then
    export PATH="$HOME/.local/bin:$PATH"
    # Make sure new Terminal windows find `claude` too.
    if ! grep -qs '.local/bin' "$HOME/.zprofile"; then
      printf '\nexport PATH="$HOME/.local/bin:$PATH"\n' >> "$HOME/.zprofile"
    fi
    if command -v claude >/dev/null 2>&1; then
      ok "Claude Code installed. The first time you run it, it will ask you to log in."
      mark_installed "Claude Code"
      return 0
    fi
  fi
  missing "Claude Code didn't install (see above)."
  mark_skipped "Claude Code (installer failed — see https://docs.claude.com/en/docs/claude-code/setup)"
  return 1
}


# =============================================================================
#  STEP 8 — The protospec command
#  A link in Homebrew's bin folder to bin/protospec inside a cached copy of the
#  template. The command refreshes that copy on every run, so it never goes stale.
# =============================================================================
PROTOSPEC_REPO="WIS-Product-Engineering/protospec"
PROTOSPEC_CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/protospec/template"

step_protospec_cli() {
  section "STEP 8 of 9 — The protospec command"
  info "This adds the 'protospec' command, which creates a new project in one go:  protospec new <name>"

  local bindir=""
  [ -n "$BREW_PREFIX" ] && bindir="$BREW_PREFIX/bin"
  if [ -z "$bindir" ]; then
    warn "Homebrew isn't available yet, so there's nowhere to put the command."
    mark_skipped "protospec command (needs Homebrew)"
    return 1
  fi

  if [ -L "$bindir/protospec" ] && [ -d "$PROTOSPEC_CACHE/.git" ]; then
    ok "The protospec command is already installed."
    mark_already "protospec command"
    return 0
  fi

  if ! { command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; }; then
    warn "This needs the GitHub login from step 5 — re-run this script once that's done."
    mark_skipped "protospec command (needs GitHub login)"
    return 1
  fi

  plan "download the protospec template (to $PROTOSPEC_CACHE) and add the 'protospec' command."
  if [ ! -d "$PROTOSPEC_CACHE/.git" ]; then
    mkdir -p "$(dirname "$PROTOSPEC_CACHE")"
    if ! gh repo clone "$PROTOSPEC_REPO" "$PROTOSPEC_CACHE" -- -q; then
      missing "Couldn't download the protospec template. Check you can open https://github.com/$PROTOSPEC_REPO"
      mark_skipped "protospec command (no access to $PROTOSPEC_REPO)"
      return 1
    fi
  fi
  if ln -sf "$PROTOSPEC_CACHE/bin/protospec" "$bindir/protospec"; then
    ok "Installed. Create a project any time with:  protospec new <name>"
    mark_installed "protospec command"
  else
    missing "Couldn't add the command to $bindir."
    mark_skipped "protospec command (couldn't write to $bindir)"
    return 1
  fi
}


# =============================================================================
#  STEP 9 — Your project
#  Run inside a project folder: install its building blocks (npm install).
#  Run anywhere else (e.g. straight from the one-line installer): offer to create
#  a new project or open an existing one.
# =============================================================================
PROJECT_DIR=""

step_project() {
  section "STEP 9 of 9 — Your project"

  if [ -f "$SCRIPT_DIR/package.json" ]; then
    step_npm_install
    if [ -f "$SCRIPT_DIR/.protospec.json" ]; then
      PROJECT_DIR="$SCRIPT_DIR"
      return 0
    fi
  fi

  if ! command -v protospec >/dev/null 2>&1; then
    info "Skipping for now — the protospec command isn't installed yet (see above)."
    return 0
  fi
  if ! have_tty; then
    info "When you're ready, create a project with:  protospec new <name>"
    return 0
  fi

  local choice name where
  cat <<EOF

   What would you like to do?
     ${BOLD}1)${RESET} Start a new project
     ${BOLD}2)${RESET} Open an existing project (someone already created it)
     ${BOLD}3)${RESET} Nothing for now
EOF
  ask choice "   Choose 1, 2 or 3" "1" || choice="3"
  case "$choice" in
    1|2) ;;
    *) info "OK. Later, create a project with:  protospec new <name>"; return 0 ;;
  esac

  ask where "   Which folder should it go in?" "$HOME/Projects" || return 0
  where="${where/#\~/$HOME}"
  if [ "$choice" = "1" ]; then
    ask name "   Project name (short, with dashes — e.g. customer-program-intake)" "" || return 0
  else
    ask name "   Project name, as it appears on GitHub (e.g. customer-program-intake)" "" || return 0
  fi
  if [ -z "$name" ]; then
    info "No name given — skipping."
    return 0
  fi

  mkdir -p "$where"
  if [ "$choice" = "1" ]; then
    ( cd "$where" && protospec new "$name" ) && PROJECT_DIR="$where/$name"
  else
    ( cd "$where" && protospec open "$name" ) && PROJECT_DIR="$where/$name"
  fi
  if [ -n "$PROJECT_DIR" ]; then
    mark_installed "Project: $PROJECT_DIR"
  else
    mark_skipped "Project $name (see the message above)"
  fi
}

# Install the current folder's building blocks (used when run inside a project).
step_npm_install() {
  info "This downloads the pieces the prototype needs to run."

  if ! command -v npm >/dev/null 2>&1; then
    warn "npm isn't available yet — skipping. Re-run this script after Node.js installs."
    mark_skipped "Project dependencies (npm missing)"
    return 1
  fi

  plan "download the project's building blocks into this folder (npm install)."
  printf '   Working in: %s\n\n' "$SCRIPT_DIR"

  # Run in a subshell so we don't permanently change directories.
  if ( cd "$SCRIPT_DIR" && npm install ); then
    ok "Project is ready to run."
    mark_installed "Project dependencies"
  else
    missing "Something went wrong installing project dependencies (see above)."
    mark_skipped "Project dependencies (npm install failed)"
  fi
}


# =============================================================================
#  FINAL SUMMARY + next steps.
# =============================================================================
print_summary() {
  section "All done — here's the recap"

  if [ "${#INSTALLED[@]}" -gt 0 ]; then
    printf '%s%sInstalled / set up this time:%s\n' "$BOLD" "$GREEN" "$RESET"
    local item; for item in "${INSTALLED[@]}"; do printf '   %s✓%s %s\n' "$GREEN" "$RESET" "$item"; done
  fi

  if [ "${#ALREADY[@]}" -gt 0 ]; then
    printf '\n%sAlready in place (no change needed):%s\n' "$BOLD" "$RESET"
    local item; for item in "${ALREADY[@]}"; do printf '   %s•%s %s\n' "$BLUE" "$RESET" "$item"; done
  fi

  if [ "${#SKIPPED[@]}" -gt 0 ]; then
    printf '\n%s%sNeeds your attention:%s\n' "$BOLD" "$YELLOW" "$RESET"
    local item; for item in "${SKIPPED[@]}"; do printf '   %s⚠%s  %s\n' "$YELLOW" "$RESET" "$item"; done
    printf '   %sTip: it is safe to run ./bootstrap.sh again to finish these.%s\n' "$DIM" "$RESET"
  fi

  cat <<EOF

${BOLD}What's next:${RESET}

EOF

  if [ -n "$PROJECT_DIR" ]; then
    cat <<EOF
  ${BOLD}Start working:${RESET} open a new Terminal window and run
        ${BLUE}cd "$PROJECT_DIR" && claude${RESET}
     Then just tell Claude what you're building, in plain English.

  ${BOLD}See the prototype in your browser:${RESET} in that folder, run ${BLUE}npm run dev${RESET}
     and open the link it prints (usually http://localhost:5173).

EOF
  else
    cat <<EOF
  ${BOLD}Create a project:${RESET} open a new Terminal window and run
        ${BLUE}protospec new <name>${RESET}
     It creates the project folder and its GitHub repo. Then ${BLUE}cd <name> && claude${RESET}.

EOF
  fi

  if [ "$FATAL" -eq 1 ]; then
    warn "One core step didn't finish. Please re-run ./bootstrap.sh after handling the note(s) above."
  else
    printf '%s%sReady to go — nice work getting set up! 🎉%s\n\n' "$BOLD" "$GREEN" "$RESET"
  fi
}


# =============================================================================
#  MAIN
# =============================================================================
main() {
  printf '\n%s%s================================================================%s\n' "$BOLD" "$BLUE" "$RESET"
  printf '%s  protospec — setup helper%s\n' "$BOLD" "$RESET"
  printf '%s  Getting your Mac ready to run and save the prototype.%s\n' "$DIM" "$RESET"
  printf '%s%s================================================================%s\n' "$BOLD" "$BLUE" "$RESET"
  printf '\n  I will check each thing you need, install only what is missing, and\n'
  printf '  explain every step. This is safe to run more than once.\n'

  preflight_os_check

  # If already on brew (from a prior run), make it usable this session up front.
  load_brew_into_path >/dev/null 2>&1 || true

  step_xcode_clt
  step_homebrew
  step_git
  step_node
  step_github_access
  step_git_identity
  step_claude_code
  step_protospec_cli
  step_project

  print_summary
}

main "$@"
