#!/usr/bin/env bash
#
# tenczar.dev — fresh Mac setup script
#
# Bootstraps Homebrew + a curated terminal stack (Ghostty, Starship, Eza,
# Zoxide, FZF, Oh My Bash, Monaspice Nerd Font) and lays down personal
# dotfiles for bash, ghostty, and starship.
#
# Safe to re-run: every step is idempotent and skips work that's already done.

set -e
set -o pipefail

# ---------------------------------------------------------------------------
# Logging — tee everything to ~/setup_log.txt
# ---------------------------------------------------------------------------
LOG_FILE="$HOME/setup_log.txt"
: > "$LOG_FILE"
exec > >(tee -a "$LOG_FILE") 2>&1

# ---------------------------------------------------------------------------
# Colors
# ---------------------------------------------------------------------------
if [ -t 1 ]; then
  RED=$'\033[0;31m'
  GREEN=$'\033[0;32m'
  YELLOW=$'\033[0;33m'
  BLUE=$'\033[0;34m'
  CYAN=$'\033[0;36m'
  MAGENTA=$'\033[0;35m'
  BOLD=$'\033[1m'
  RESET=$'\033[0m'
else
  RED=""; GREEN=""; YELLOW=""; BLUE=""; CYAN=""; MAGENTA=""; BOLD=""; RESET=""
fi

CHECK="${GREEN}✓${RESET}"
CROSS="${RED}✗${RESET}"
ARROW="${YELLOW}➜${RESET}"

# ---------------------------------------------------------------------------
# Tracking lists for the final summary
# ---------------------------------------------------------------------------
SKIPPED=()
INSTALLED=()
WROTE=()

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
banner() {
  local msg="$1"
  local width=70
  local line
  line=$(printf '═%.0s' $(seq 1 $width))
  echo
  echo "${CYAN}╔${line}╗${RESET}"
  printf "${CYAN}║${RESET} ${BOLD}%-*s${RESET} ${CYAN}║${RESET}\n" $((width - 1)) "$msg"
  echo "${CYAN}╚${line}╝${RESET}"
}

log_info()    { echo "${BLUE}[INFO]${RESET}    $*"; }
log_skip()    { echo "${CHECK} ${GREEN}[SKIP]${RESET}    $*"; }
log_done()    { echo "${CHECK} ${GREEN}[OK]${RESET}      $*"; }
log_warn()    { echo "${ARROW} ${YELLOW}[WARN]${RESET}    $*"; }
log_error()   { echo "${CROSS} ${RED}[ERROR]${RESET}   $*"; }
log_write()   { echo "${CHECK} ${GREEN}[WROTE]${RESET}   $*"; }
log_progress(){ echo "${ARROW} ${YELLOW}[INSTALL]${RESET} $*"; }

# Animated progress indicator for a backgrounded PID.
spinner() {
  local pid=$1
  local label="$2"
  local width=30
  local i=0
  local frames='|/-\'
  tput civis 2>/dev/null || true
  while kill -0 "$pid" 2>/dev/null; do
    local pos=$(( i % width ))
    local bar=""
    local j=0
    while [ $j -lt $width ]; do
      if [ $j -eq $pos ]; then
        bar="${bar}█"
      else
        bar="${bar}░"
      fi
      j=$((j + 1))
    done
    local frame="${frames:$((i % 4)):1}"
    printf "\r  ${YELLOW}%s${RESET} [${CYAN}%s${RESET}] %s" "$frame" "$bar" "$label"
    i=$((i + 1))
    sleep 0.1
  done
  printf "\r  ${GREEN}✓${RESET} [%s] %s\n" "$(printf '█%.0s' $(seq 1 $width))" "$label done"
  tput cnorm 2>/dev/null || true
  wait "$pid"
}

# Run a command in the background, log its output to the main log only,
# and show a spinner while it runs.
run_with_spinner() {
  local label="$1"
  shift
  ("$@") >>"$LOG_FILE" 2>&1 &
  local pid=$!
  spinner "$pid" "$label"
}

is_brew_formula_installed() {
  brew list --formula --versions "$1" >/dev/null 2>&1
}

is_brew_cask_installed() {
  brew list --cask --versions "$1" >/dev/null 2>&1
}

# ---------------------------------------------------------------------------
# Step 0 — ASCII banner
# ---------------------------------------------------------------------------
clear || true
cat <<'BANNER'
[1;36m
  ████████╗███████╗███╗   ██╗ ██████╗███████╗ █████╗ ██████╗     ██████╗ ███████╗██╗   ██╗
  ╚══██╔══╝██╔════╝████╗  ██║██╔════╝╚══███╔╝██╔══██╗██╔══██╗    ██╔══██╗██╔════╝██║   ██║
     ██║   █████╗  ██╔██╗ ██║██║       ███╔╝ ███████║██████╔╝    ██║  ██║█████╗  ██║   ██║
     ██║   ██╔══╝  ██║╚██╗██║██║      ███╔╝  ██╔══██║██╔══██╗    ██║  ██║██╔══╝  ╚██╗ ██╔╝
     ██║   ███████╗██║ ╚████║╚██████╗███████╗██║  ██║██║  ██║██╗ ██████╔╝███████╗ ╚████╔╝
     ╚═╝   ╚══════╝╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝ ╚═════╝ ╚══════╝  ╚═══╝
[0m
[1;35m                              fresh-mac setup • tenczar.dev[0m
BANNER
echo
sleep 1

# ---------------------------------------------------------------------------
# Step 1 — Homebrew
# ---------------------------------------------------------------------------
banner "STEP 1 — Homebrew"

if command -v brew >/dev/null 2>&1; then
  log_skip "Homebrew is already installed ($(brew --version | head -n1))"
  SKIPPED+=("Homebrew")
else
  log_progress "Installing Homebrew via official install script..."
  run_with_spinner "Installing Homebrew" /bin/bash -c \
    'NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
  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)"
  else
    log_error "Homebrew install finished but brew binary not found."
    exit 1
  fi
  log_done "Homebrew installed and added to PATH"
  INSTALLED+=("Homebrew")
fi

# Make sure brew is on PATH for the rest of this session even if it was
# already installed but the parent shell didn't have it sourced.
if ! command -v brew >/dev/null 2>&1; then
  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)"
  fi
fi

# ---------------------------------------------------------------------------
# Step 2 — Monaspice Nerd Font (must precede ghostty config)
# ---------------------------------------------------------------------------
banner "STEP 2 — Monaspice Nerd Font"

if is_brew_cask_installed font-monaspice-nerd-font; then
  log_skip "font-monaspice-nerd-font already installed"
  SKIPPED+=("font-monaspice-nerd-font")
else
  log_progress "Installing font-monaspice-nerd-font..."
  run_with_spinner "Installing font-monaspice-nerd-font" \
    brew install --cask font-monaspice-nerd-font
  log_done "font-monaspice-nerd-font installed"
  INSTALLED+=("font-monaspice-nerd-font")
fi

# ---------------------------------------------------------------------------
# Step 3 — Core packages
# ---------------------------------------------------------------------------
banner "STEP 3 — Core packages"

install_cask() {
  local cask="$1"
  if is_brew_cask_installed "$cask"; then
    log_skip "$cask (cask) already installed"
    SKIPPED+=("$cask")
  else
    log_progress "Installing $cask (cask)..."
    run_with_spinner "Installing $cask" brew install --cask "$cask"
    log_done "$cask installed"
    INSTALLED+=("$cask")
  fi
}

install_formula() {
  local formula="$1"
  if is_brew_formula_installed "$formula"; then
    log_skip "$formula already installed"
    SKIPPED+=("$formula")
  else
    log_progress "Installing $formula..."
    run_with_spinner "Installing $formula" brew install "$formula"
    log_done "$formula installed"
    INSTALLED+=("$formula")
  fi
}

install_cask    ghostty
install_formula starship
install_formula eza
install_formula zoxide
install_formula fzf
install_formula bash-completion@2
install_formula neofetch

# ---------------------------------------------------------------------------
# Step 4 — Oh My Bash
# ---------------------------------------------------------------------------
banner "STEP 4 — Oh My Bash"

if [ -d "$HOME/.oh-my-bash" ]; then
  log_skip "Oh My Bash already installed at ~/.oh-my-bash"
  SKIPPED+=("Oh My Bash")
else
  log_progress "Installing Oh My Bash (non-interactive)..."
  run_with_spinner "Installing Oh My Bash" /bin/bash -c \
    'bash -c "$(curl -fsSL https://raw.githubusercontent.com/ohmybash/oh-my-bash/master/tools/install.sh)" "" --unattended'
  log_done "Oh My Bash installed"
  INSTALLED+=("Oh My Bash")
fi

# ---------------------------------------------------------------------------
# Step 5 — Oh My Zsh
# ---------------------------------------------------------------------------
banner "STEP 5 — Oh My Zsh"

if [ -d "$HOME/.oh-my-zsh" ]; then
  log_skip "Oh My Zsh already installed at ~/.oh-my-zsh"
  SKIPPED+=("Oh My Zsh")
else
  log_progress "Installing Oh My Zsh (non-interactive, --keep-zshrc)..."
  # RUNZSH=no  → don't drop into zsh after install
  # CHSH=no    → don't change the login shell (user can do it later)
  # --unattended is also passed for safety
  # We'll overwrite .zshrc ourselves later so --keep-zshrc avoids any clobber races.
  run_with_spinner "Installing Oh My Zsh" /bin/bash -c \
    'RUNZSH=no CHSH=no sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended --keep-zshrc'
  log_done "Oh My Zsh installed"
  INSTALLED+=("Oh My Zsh")
fi

# ---------------------------------------------------------------------------
# Step 6 — Powerlevel10k (installed only — user runs `p10k configure` later)
# ---------------------------------------------------------------------------
banner "STEP 6 — Powerlevel10k"

P10K_DIR="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k"
if [ -d "$P10K_DIR" ]; then
  log_skip "Powerlevel10k already cloned at $P10K_DIR"
  SKIPPED+=("powerlevel10k")
else
  log_progress "Cloning Powerlevel10k into $P10K_DIR..."
  run_with_spinner "Cloning powerlevel10k" \
    git clone --depth=1 https://github.com/romkatv/powerlevel10k.git "$P10K_DIR"
  log_done "Powerlevel10k cloned"
  INSTALLED+=("powerlevel10k")
fi

# ---------------------------------------------------------------------------
# Step 7 — Starship nerd-font preset
# ---------------------------------------------------------------------------
banner "STEP 7 — Starship preset"

mkdir -p "$HOME/.config"
starship preset nerd-font-symbols -o "$HOME/.config/starship.toml"
log_done "Applied starship preset 'nerd-font-symbols' to ~/.config/starship.toml"

# ---------------------------------------------------------------------------
# Step 8 — Write ~/.bashrc
# ---------------------------------------------------------------------------
banner "STEP 8 — Write ~/.bashrc"

cat > "$HOME/.bashrc" <<'BASHRC_EOF'
# Enable the subsequent settings only in interactive sessions
case $- in
  *i*) ;;
    *) return;;
esac

# Homebrew (must be early so everything else can find brew packages)
eval "$(/opt/homebrew/bin/brew shellenv)"

# Bash completion (must be before Oh My Bash)
[[ -r "/opt/homebrew/etc/profile.d/bash_completion.sh" ]] && . "/opt/homebrew/etc/profile.d/bash_completion.sh"

# Path to your oh-my-bash installation.
export OSH='/Users/j10/.oh-my-bash'

OSH_THEME="font"

OMB_USE_SUDO=true

completions=(
  git
  composer
  ssh
)

aliases=(
  general
)

plugins=(
  git
  bashmarks
)

source "$OSH"/oh-my-bash.sh

# Starship
eval "$(starship init bash)"

# EZA
alias ls='eza --icons'
alias ll='eza --icons --long --all'

# Zoxide
eval "$(zoxide init bash)"
alias cd='z'

# FZF
eval "$(fzf --bash)"



alias n='neofetch'
BASHRC_EOF

log_write "~/.bashrc"
WROTE+=("~/.bashrc")

# ---------------------------------------------------------------------------
# Step 9 — Write ~/.zshrc and ~/.zprofile
# ---------------------------------------------------------------------------
banner "STEP 9 — Write zsh dotfiles"

# ~/.zprofile — sourced by login zsh (incl. macOS default Terminal.app).
# This guarantees brew is on PATH for zsh sessions outside Ghostty.
cat > "$HOME/.zprofile" <<'ZPROFILE_EOF'
# Homebrew on PATH for login zsh sessions
eval "$(/opt/homebrew/bin/brew shellenv)"
ZPROFILE_EOF
log_write "~/.zprofile"
WROTE+=("~/.zprofile")

# ~/.zshrc — minimal config: oh-my-zsh + powerlevel10k + eza + zoxide.
# Run `p10k configure` after first launch to generate ~/.p10k.zsh.
cat > "$HOME/.zshrc" <<'ZSHRC_EOF'
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

# Homebrew (in case .zprofile wasn't sourced — e.g. non-login shell)
eval "$(/opt/homebrew/bin/brew shellenv)"

# Oh My Zsh
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="powerlevel10k/powerlevel10k"
plugins=(git)
source "$ZSH/oh-my-zsh.sh"

# To customize the Powerlevel10k prompt, run `p10k configure` and then this
# file will source the generated ~/.p10k.zsh on next launch.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh

# eza
alias ls='eza --icons'
alias ll='eza --icons --long --all'

# zoxide
eval "$(zoxide init zsh)"
alias cd='z'
ZSHRC_EOF
log_write "~/.zshrc"
WROTE+=("~/.zshrc")

# ---------------------------------------------------------------------------
# Step 10 — Write ~/.config/ghostty/config
# ---------------------------------------------------------------------------
banner "STEP 10 — Write Ghostty config"

mkdir -p "$HOME/.config/ghostty"

cat > "$HOME/.config/ghostty/config" <<'GHOSTTY_EOF'
# Appearance
theme = tokyo-black-saturated
font-family = "MonaspiceNe Nerd Font Mono"
font-size = 14
cursor-style = block
background-opacity = 1
macos-titlebar-style = transparent
window-padding-x = 10
window-padding-y = 10
window-padding-balance = true
window-save-state = always

# Quality of life
mouse-hide-while-typing = true
mouse-scroll-multiplier = 2
copy-on-select = true
unfocused-split-opacity = 1

# Custom split keybinds (override defaults if you want)
keybind = cmd+shift+right=new_split:right
keybind = cmd+shift+down=new_split:down
keybind = cmd+alt+left=goto_split:left
keybind = cmd+alt+right=goto_split:right
keybind = cmd+alt+up=goto_split:up
keybind = cmd+alt+down=goto_split:down
keybind = cmd+shift+e=equalize_splits
keybind = cmd+shift+z=toggle_split_zoom

# Quake-style drop-down terminal (cmd+` to toggle)
keybind = global:cmd+grave_accent=toggle_quick_terminal

# Bash defaults
command = /bin/bash
GHOSTTY_EOF

log_write "~/.config/ghostty/config"
WROTE+=("~/.config/ghostty/config")

# ---------------------------------------------------------------------------
# Step 11 — Write Ghostty themes
# ---------------------------------------------------------------------------
banner "STEP 11 — Write Ghostty themes"

mkdir -p "$HOME/.config/ghostty/themes"

cat > "$HOME/.config/ghostty/themes/tokyo-black-saturated" <<'THEME_EOF'
# Tokyo Night Dark Enhanced (Saturated) for Ghostty
background = 0a0a0d
foreground = a9b1d6
cursor-color = 7aa2f7
selection-background = 1a1b2e
selection-foreground = c0caf5

# Normal colors (0-7)
palette = 0=#363b54
palette = 1=#ff3d6b
palette = 2=#00d4a8
palette = 3=#ffbe00
palette = 4=#4d8fff
palette = 5=#d45aff
palette = 6=#00d4ff
palette = 7=#787c99

# Bright colors (8-15)
palette = 8=#363b54
palette = 9=#ff3d6b
palette = 10=#00d4a8
palette = 11=#ffbe00
palette = 12=#4d8fff
palette = 13=#d45aff
palette = 14=#00d4ff
palette = 15=#acb0d0
THEME_EOF

log_write "~/.config/ghostty/themes/tokyo-black-saturated"
WROTE+=("~/.config/ghostty/themes/tokyo-black-saturated")

# ---------------------------------------------------------------------------
# Final summary
# ---------------------------------------------------------------------------
banner "SETUP COMPLETE — SUMMARY"

echo
echo "${BOLD}${GREEN}Already installed (skipped):${RESET}"
if [ ${#SKIPPED[@]} -eq 0 ]; then
  echo "  (none)"
else
  for item in "${SKIPPED[@]}"; do
    echo "  ${CHECK} $item"
  done
fi

echo
echo "${BOLD}${YELLOW}Freshly installed:${RESET}"
if [ ${#INSTALLED[@]} -eq 0 ]; then
  echo "  (none)"
else
  for item in "${INSTALLED[@]}"; do
    echo "  ${ARROW} $item"
  done
fi

echo
echo "${BOLD}${CYAN}Config files written:${RESET}"
for item in "${WROTE[@]}"; do
  echo "  ${CHECK} $item"
done

echo
echo "${BOLD}${MAGENTA}Log file:${RESET} $LOG_FILE"
echo
echo "${BOLD}${YELLOW}Next step for zsh users:${RESET}"
echo "  Open a new zsh session (or run ${BOLD}exec zsh${RESET}) and execute:"
echo "    ${BOLD}p10k configure${RESET}"
echo "  This generates ${BOLD}~/.p10k.zsh${RESET}, which the new ~/.zshrc will source on next launch."
echo
echo "${BOLD}${GREEN}╔══════════════════════════════════════════════════════════════════════╗${RESET}"
echo "${BOLD}${GREEN}║                     ✓  All done — tenczar.dev                        ║${RESET}"
echo "${BOLD}${GREEN}║   Restart your terminal (or open Ghostty) to load the new config.    ║${RESET}"
echo "${BOLD}${GREEN}╚══════════════════════════════════════════════════════════════════════╝${RESET}"
echo
