#!/bin/bash
set -euo pipefail

# Dry run: ./install.sh --dry-run  OR  DRY_RUN=1 ./install.sh
if [[ "${1:-}" == "--dry-run" ]]; then
  DRY_RUN=1
  shift
fi
DRY_RUN=${DRY_RUN:-0}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "🍎 macOS Apple Silicon Bootstrap Starting..."
if [[ "$DRY_RUN" == "1" ]]; then
  echo "🧪 DRY RUN — no installs, file edits, SSH/git changes, or GUI opens (brew queries still run if Homebrew exists)."
fi

# Resolve Homebrew prefix (Apple Silicon vs Intel)
init_brew_shellenv() {
  if [[ -x /opt/homebrew/bin/brew ]]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  elif [[ -x /usr/local/bin/brew ]]; then
    eval "$(/usr/local/bin/brew shellenv)"
  elif command -v brew &>/dev/null; then
    eval "$(brew shellenv)"
  else
    echo "❌ Homebrew not found after install. Add brew to PATH and re-run." >&2
    exit 1
  fi
}

###############################################################################
# 1. Xcode Command Line Tools
###############################################################################
if ! xcode-select -p &>/dev/null; then
  echo "🛠 Installing Xcode Command Line Tools..."
  if [[ "$DRY_RUN" == "1" ]]; then
    echo "[dry-run] Would run xcode-select --install (finish GUI, then re-run for real)."
  else
    xcode-select --install || true
  fi
  echo "➡️  Finish the CLT install popup, then re-run this script if needed."
fi

###############################################################################
# 2. Homebrew (Apple Silicon or Intel)
###############################################################################
if ! command -v brew &>/dev/null && [[ ! -x /opt/homebrew/bin/brew && ! -x /usr/local/bin/brew ]]; then
  echo "🍺 Installing Homebrew..."
  if [[ "$DRY_RUN" == "1" ]]; then
    echo "[dry-run] Would run official Homebrew install script (curl | bash)."
  else
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  fi
fi

if [[ "$DRY_RUN" == "1" ]] && ! command -v brew &>/dev/null && [[ ! -x /opt/homebrew/bin/brew && ! -x /usr/local/bin/brew ]]; then
  echo "➡️  Install Homebrew (or drop --dry-run on a Mac that already has it) to simulate brew steps."
  echo "✅ Dry run finished."
  exit 0
fi

init_brew_shellenv

if [[ "$DRY_RUN" == "1" ]]; then
  brew() {
    case "${1:-}" in
      install|reinstall|uninstall|upgrade)
        echo "[dry-run] brew $*"
        return 0
        ;;
      update|cleanup)
        echo "[dry-run] brew $*"
        return 0
        ;;
    esac
    command brew "$@"
  }
fi

###############################################################################
# 3. Update Homebrew
###############################################################################
echo "🔄 Updating Homebrew metadata..."
brew update
echo "➡️  Run brew upgrade when you want to upgrade installed packages."

###############################################################################
# 4. CLI Tools
###############################################################################
CLI_TOOLS=(
  git
  node
  nvm
  python
  wget
  yarn
  go
  minikube
  gh
  docker
)

echo "📦 Installing CLI tools..."
for tool in "${CLI_TOOLS[@]}"; do
  if brew list --formula "$tool" &>/dev/null; then
    echo "✔ $tool already installed"
  else
    brew install "$tool"
  fi
done

###############################################################################
# 5. Shell (Oh My Zsh + ~/.zshrc from repo)
###############################################################################
echo "🟢 Configuring Zsh..."
ZSHRC_SRC="$SCRIPT_DIR/dotfiles/.zshrc"
if [[ "$DRY_RUN" == "1" ]]; then
  echo "[dry-run] Would mkdir -p ~/.nvm; install Oh My Zsh if missing; deploy dotfiles/.zshrc → ~/.zshrc"
else
  mkdir -p "$HOME/.nvm"
  if [[ ! -d "$HOME/.oh-my-zsh" ]]; then
    echo "📥 Installing Oh My Zsh (unattended, leaves default shell unchanged)..."
    RUNZSH=no CHSH=no sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
  fi
  if [[ -f "$ZSHRC_SRC" ]]; then
    if [[ -f "$HOME/.zshrc" ]] && ! cmp -s "$ZSHRC_SRC" "$HOME/.zshrc"; then
      bak="${HOME}/.zshrc.pre-mac-setup.$(date +%Y%m%d%H%M%S)"
      cp "$HOME/.zshrc" "$bak"
      echo "➡️  Previous ~/.zshrc saved as $bak"
    fi
    cp "$ZSHRC_SRC" "$HOME/.zshrc"
    echo "✔ Installed ~/.zshrc from Mac_Setup dotfiles"
  else
    echo "⚠️  Missing $ZSHRC_SRC — add dotfiles/.zshrc to the repo for a versioned shell config."
  fi
fi

###############################################################################
# 6. GUI Applications
###############################################################################
GUI_APPS=(
  brave
  cursor
  ghostty
  orbstack
  raycast
)

echo "🖥 Installing GUI applications..."
for app in "${GUI_APPS[@]}"; do
  if brew list --cask "$app" &>/dev/null; then
    echo "✔ $app already installed"
  else
    brew install --cask "$app"
  fi
done

# ###############################################################################
# # 6a. Ghostty configuration
# ###############################################################################
# echo "👻 Configuring Ghostty..."

# GHOSTTY_CONFIG_DIR="$HOME/.config/ghostty"
# GHOSTTY_CONFIG_FILE="$GHOSTTY_CONFIG_DIR/config"

# if [[ "$DRY_RUN" == "1" ]]; then
#   echo "[dry-run] Would create $GHOSTTY_CONFIG_FILE"
# else
#   mkdir -p "$GHOSTTY_CONFIG_DIR"

#   cat > "$GHOSTTY_CONFIG_FILE" <<EOF
# background = 000000
# foreground = d0d0d0
# font-size = 15
# window-padding-x = 12
# window-padding-y = 12
# split-divider-color = #44475a
# macos-titlebar-style = tabs
# focus-follows-mouse = true
# font-thicken = true
# working-directory = ~/Developer

# command = /bin/zsh
# EOF

#   echo "✔ Ghostty configuration installed at $GHOSTTY_CONFIG_FILE"
# fi

###############################################################################
# 6b. Raycast config (.rayconfig → Import Settings & Data + passphrase)
###############################################################################
RAYCONFIG=""
shopt -s nullglob
for f in "$SCRIPT_DIR"/*.rayconfig; do
  if [[ -z "$RAYCONFIG" || "$f" -nt "$RAYCONFIG" ]]; then
    RAYCONFIG=$f
  fi
done
shopt -u nullglob

if [[ -n "$RAYCONFIG" ]]; then
  echo "🎯 Raycast backup found (newest .rayconfig next to this script):"
  echo "   $RAYCONFIG"
  if [[ "$DRY_RUN" == "1" ]]; then
    echo "[dry-run] Would open -a Raycast and open -R \"$RAYCONFIG\" in Finder."
  else
    open -a Raycast 2>/dev/null || true
    open -R "$RAYCONFIG" 2>/dev/null || true
  fi
  echo "➡️  In Raycast run: Import Settings & Data → choose the file above (Finder highlights it)."
  echo "➡️  When prompted, enter your Raycast export passphrase (the one used when this backup was exported)."
else
  echo "ℹ️  No .rayconfig in $SCRIPT_DIR — add a backup beside install.sh to auto-open import hints."
fi

###############################################################################
# 7. GitHub SSH (modern + keychain)
###############################################################################
EMAIL="maheshkasbe010@gmail.com"

echo "🔐 Setting up GitHub SSH..."
if [[ "$DRY_RUN" == "1" ]]; then
  echo "[dry-run] Would mkdir ~/.ssh, chmod 700, ssh-keygen id_ed25519 if missing, ssh-agent, ssh-add, append github Host to ~/.ssh/config"
  echo "📋 GitHub SSH Public Key (would show):"
  if [[ -f ~/.ssh/id_ed25519.pub ]]; then
    cat ~/.ssh/id_ed25519.pub
  else
    echo "[dry-run] (no ~/.ssh/id_ed25519.pub yet)"
  fi
  echo "➡️  Add this key to: https://github.com/settings/keys"
else
mkdir -p ~/.ssh
chmod 700 ~/.ssh

if [[ ! -f ~/.ssh/id_ed25519 ]]; then
  if [[ -t 0 ]]; then
    ssh-keygen -t ed25519 -C "$EMAIL" -f ~/.ssh/id_ed25519
  else
    ssh-keygen -t ed25519 -C "$EMAIL" -f ~/.ssh/id_ed25519 -N "" -q
  fi
fi

eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/id_ed25519 2>/dev/null || true

if ! grep -q "Host github.com" ~/.ssh/config 2>/dev/null; then
cat <<EOL >> ~/.ssh/config

Host github.com
  HostName github.com
  User git
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_ed25519
EOL
fi

echo "📋 GitHub SSH Public Key:"
cat ~/.ssh/id_ed25519.pub
echo "➡️  Add this key to: https://github.com/settings/keys"
fi

###############################################################################
# 8. Git Configuration
###############################################################################
echo "🧾 Configuring Git..."
if [[ "$DRY_RUN" == "1" ]]; then
  echo "[dry-run] git config --global user.name / user.email / init.defaultBranch / core.editor"
else
git config --global user.name "Mahesh Kasbe"
git config --global user.email "$EMAIL"
git config --global init.defaultBranch main
git config --global core.editor "nano"
fi

###############################################################################
# 9. GitHub CLI Auth (optional)
###############################################################################
choice=n
if [[ "$DRY_RUN" == "1" ]]; then
  echo "[dry-run] Skipping gh auth login prompt"
  choice=n
elif [[ -t 0 ]] && read -r -p "🔑 Authenticate GitHub CLI now? (y/n): " choice </dev/tty; then
  :
else
  choice=n
fi
if [[ "${choice:-n}" == "y" || "${choice:-n}" == "Y" ]]; then
  gh auth login
else
  echo "➡️  Run later with: gh auth login"
fi

###############################################################################
# 10. Cleanup
###############################################################################
echo "🧹 Cleaning up..."
brew cleanup
open "cursor://profile/github/e32d9487bbfe1d77c74bd7085802e8dd"

###############################################################################
# Final Notes
###############################################################################
if [[ "$DRY_RUN" == "1" ]]; then
  echo "✅ Dry run complete (nothing was changed)."
else
  echo "✅ Setup complete!"
fi
echo "⚠️  IMPORTANT:"
echo "   • Open Docker.app once to finish setup"
echo "   • Open a new terminal tab or: source ~/.zshrc (Oh My Zsh, NVM, JAVA, paths)"
echo "   • Finish Raycast import (Import Settings & Data + passphrase) if Finder opened a .rayconfig"
echo "🚀 Happy hacking!"
