#!/usr/bin/env bash
# setup-mac.sh — devAlice Mac initial setup automation
# Companion to: https://devalice.vercel.app/mac/initial-setup
#
# Idempotent. Safe to re-run.
#
# Usage (recommended — verify SHA-256 first):
#   curl -fsSL https://devalice.vercel.app/assets/mac/initial-setup/setup-mac.sh -o setup-mac.sh
#   shasum -a 256 setup-mac.sh   # compare with SHA-256 in the article
#   bash setup-mac.sh

set -eu
set -o pipefail

GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
RESET='\033[0m'

log()  { printf "${GREEN}[setup-mac]${RESET} %s\n" "$*"; }
warn() { printf "${YELLOW}[setup-mac]${RESET} %s\n" "$*"; }
err()  { printf "${RED}[setup-mac]${RESET} %s\n" "$*" >&2; }

require_macos() {
  if [ "$(uname)" != "Darwin" ]; then
    err "macOS only. Detected: $(uname)"
    exit 1
  fi
  local v
  v=$(sw_vers -productVersion | cut -d. -f1)
  if [ "$v" -lt 14 ]; then
    err "macOS 14 (Sonoma) or later required. Detected: $(sw_vers -productVersion)"
    exit 1
  fi
}

configure_system_settings() {
  log "Step 1/6: macOS system settings..."

  defaults write -g KeyRepeat -int 1
  defaults write -g InitialKeyRepeat -int 10

  defaults write com.apple.AppleMultitouchTrackpad Clicking -bool true
  defaults -currentHost write -g com.apple.mouse.tapBehavior -int 1

  defaults write com.apple.finder AppleShowAllFiles -bool true
  defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
  defaults write -g AppleShowAllExtensions -bool true

  defaults write com.apple.dock autohide -bool true
  defaults write com.apple.dock autohide-delay -float 0
  defaults write com.apple.dock autohide-time-modifier -float 0.15

  mkdir -p "$HOME/Pictures/Screenshots"
  defaults write com.apple.screencapture location "$HOME/Pictures/Screenshots"
  defaults write com.apple.screencapture type png

  killall Finder Dock SystemUIServer >/dev/null 2>&1 || true
  log "  OK — applied. (re-login required for key repeat)"
}

install_xcode_clt() {
  log "Step 2/6: Xcode Command Line Tools..."
  if xcode-select -p >/dev/null 2>&1; then
    log "  OK — already installed: $(xcode-select -p)"
    return
  fi
  warn "  Installing CLT (GUI dialog will appear)..."
  xcode-select --install || true
  warn "  After installer finishes, re-run this script."
  exit 0
}

install_homebrew() {
  log "Step 3/6: Homebrew..."
  if command -v brew >/dev/null 2>&1; then
    log "  OK — already installed: $(brew --version | head -1)"
    return
  fi
  log "  Installing Homebrew..."
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  if [ -d /opt/homebrew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
    if ! grep -q "brew shellenv" "$HOME/.zprofile" 2>/dev/null; then
      echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$HOME/.zprofile"
    fi
  elif [ -d /usr/local/Homebrew ]; then
    eval "$(/usr/local/bin/brew shellenv)"
    if ! grep -q "brew shellenv" "$HOME/.zprofile" 2>/dev/null; then
      echo 'eval "$(/usr/local/bin/brew shellenv)"' >> "$HOME/.zprofile"
    fi
  fi
}

install_cli_tools() {
  log "Step 4/6: Essential CLI tools..."
  brew install git gh mise jq ripgrep fzf eza
  log "  OK — installed: git gh mise jq ripgrep fzf eza"
}

configure_git() {
  log "Step 5/6: Git global config..."

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

  if [ -n "$cur_name" ] && [ -n "$cur_email" ]; then
    log "  OK — already configured: $cur_name <$cur_email>"
  else
    if [ -t 0 ]; then
      printf "  Git user.name: "
      read -r git_name
      printf "  Git user.email: "
      read -r git_email
      git config --global user.name "$git_name"
      git config --global user.email "$git_email"
    else
      warn "  Skipped (non-interactive). Set manually:"
      warn "    git config --global user.name 'Your Name'"
      warn "    git config --global user.email 'you@example.com'"
    fi
  fi

  git config --global init.defaultBranch main
  git config --global pull.rebase false
}

generate_ssh_key() {
  log "Step 6/6: SSH key (ed25519)..."

  if [ -f "$HOME/.ssh/id_ed25519" ]; then
    log "  OK — SSH key already exists: ~/.ssh/id_ed25519"
  else
    if [ -t 0 ]; then
      local email
      email=$(git config --global user.email 2>/dev/null || echo "")
      if [ -z "$email" ]; then
        printf "  SSH key email comment: "
        read -r email
      fi
      ssh-keygen -t ed25519 -C "$email" -f "$HOME/.ssh/id_ed25519" -N ""
    else
      warn "  Skipped (non-interactive). Generate manually with: ssh-keygen -t ed25519 -C 'you@example.com'"
      return
    fi
  fi

  if ! grep -q "Host github.com" "$HOME/.ssh/config" 2>/dev/null; then
    mkdir -p "$HOME/.ssh"
    chmod 700 "$HOME/.ssh"
    cat <<'EOF' >> "$HOME/.ssh/config"

Host github.com
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_ed25519
EOF
    log "  OK — ~/.ssh/config updated for github.com"
  fi

  ssh-add --apple-use-keychain "$HOME/.ssh/id_ed25519" 2>/dev/null || true
  log "  OK — SSH key added to macOS Keychain"
}

print_next_steps() {
  echo
  log "========================================"
  log "Setup complete. Manual steps remaining:"
  log "========================================"
  echo
  echo "  1) Copy SSH public key to clipboard:"
  echo "       pbcopy < ~/.ssh/id_ed25519.pub"
  echo
  echo "  2) Register key at GitHub:"
  echo "       https://github.com/settings/ssh/new"
  echo
  echo "  3) Authenticate gh CLI (HTTPS for PRs):"
  echo "       gh auth login"
  echo
  echo "  4) Verify:"
  echo "       ssh -T git@github.com"
  echo "       gh auth status"
  echo
  echo "  5) (Optional) Re-login or restart to apply key repeat settings."
  echo
}

main() {
  require_macos
  configure_system_settings
  install_xcode_clt
  install_homebrew
  install_cli_tools
  configure_git
  generate_ssh_key
  print_next_steps
}

main "$@"
