# ~/.zshrc: a fast, framework-free Zsh config.
# Docs: https://github.com/Ralpberry-Labs/zsh-productivity
# Every section is optional: delete what you do not want.
# Personal settings and secrets go in ~/.zshrc.local (sourced at the end).

# ---------------------------------------------------------------------------
# 0. Paths
# ---------------------------------------------------------------------------
ZSH_PRODUCTIVITY_DIR=${ZSH_PRODUCTIVITY_DIR:-${${(%):-%x}:A:h}}   # folder of this file
ZPLUGDIR=${ZPLUGDIR:-${XDG_DATA_HOME:-$HOME/.local/share}/zsh/plugins}
ZCACHEDIR=${XDG_CACHE_HOME:-$HOME/.cache}/zsh
[[ -d $ZCACHEDIR ]] || mkdir -p $ZCACHEDIR

typeset -U path fpath                   # keep PATH and fpath free of duplicates
path=($HOME/.local/bin $HOME/bin $path)

# ---------------------------------------------------------------------------
# 1. Options
# ---------------------------------------------------------------------------
setopt AUTO_CD              # type a directory name to cd into it
setopt AUTO_PUSHD           # cd pushes the old dir onto the stack (cd -<TAB>)
setopt PUSHD_IGNORE_DUPS
setopt PUSHD_SILENT
setopt EXTENDED_GLOB        # ^, ~, # and (qualifiers) in globs
setopt GLOB_DOTS            # globs match dotfiles
setopt NO_CASE_GLOB         # case-insensitive globbing
setopt INTERACTIVE_COMMENTS # allow # comments at the prompt
setopt NO_BEEP
setopt NO_FLOW_CONTROL      # free up Ctrl-S / Ctrl-Q
setopt PROMPT_SUBST         # expand $(...) and ${...} in the prompt
setopt LONG_LIST_JOBS
setopt NOTIFY               # report background job status immediately

# ---------------------------------------------------------------------------
# 2. History
# ---------------------------------------------------------------------------
HISTFILE=${XDG_STATE_HOME:-$HOME/.local/state}/zsh/history
[[ -d ${HISTFILE:h} ]] || mkdir -p ${HISTFILE:h}
HISTSIZE=100000             # lines kept in memory
SAVEHIST=100000             # lines saved to $HISTFILE
setopt EXTENDED_HISTORY     # save timestamp and duration
setopt SHARE_HISTORY        # share history between open shells (implies incremental append)
setopt HIST_IGNORE_ALL_DUPS # drop older duplicates
setopt HIST_IGNORE_SPACE    # commands starting with a space are not saved (secrets!)
setopt HIST_REDUCE_BLANKS
setopt HIST_VERIFY          # !! and !$ expand into the line instead of running at once
setopt HIST_FIND_NO_DUPS

# ---------------------------------------------------------------------------
# 3. Completion
# ---------------------------------------------------------------------------
# Extra completions must be on fpath before compinit.
[[ -d $ZPLUGDIR/zsh-completions/src ]] && fpath=($ZPLUGDIR/zsh-completions/src $fpath)
[[ -d /opt/homebrew/share/zsh/site-functions ]] && fpath=(/opt/homebrew/share/zsh/site-functions $fpath)

autoload -Uz compinit
# Rebuild the completion dump at most once a day; otherwise skip the security check (-C).
if [[ -n $ZCACHEDIR/zcompdump(#qN.mh+24) || ! -f $ZCACHEDIR/zcompdump ]]; then
  compinit -d $ZCACHEDIR/zcompdump
else
  compinit -C -d $ZCACHEDIR/zcompdump
fi

zmodload zsh/complist
zstyle ':completion:*' menu select                        # arrow-key menu
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'  # case-insensitive, then fuzzy-ish
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*' group-name ''
zstyle ':completion:*:descriptions' format '%F{yellow}-- %d --%f'
zstyle ':completion:*:warnings' format '%F{red}no matches%f'
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path $ZCACHEDIR/compcache
zstyle ':completion:*' squeeze-slashes true
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*' force-list always

# ---------------------------------------------------------------------------
# 4. Key bindings (emacs mode; use `bindkey -v` for vi mode)
# ---------------------------------------------------------------------------
bindkey -e
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search edit-command-line
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
zle -N edit-command-line
bindkey '^[[A' up-line-or-beginning-search     # Up: history search with the typed prefix
bindkey '^[[B' down-line-or-beginning-search   # Down
bindkey '^[OA' up-line-or-beginning-search     # (application-mode arrow codes)
bindkey '^[OB' down-line-or-beginning-search
bindkey '^X^E' edit-command-line               # Ctrl-X Ctrl-E: edit the command in $EDITOR
bindkey '^[[1;5C' forward-word                 # Ctrl-Right
bindkey '^[[1;5D' backward-word                # Ctrl-Left
bindkey '^[[3~' delete-char                    # Delete
bindkey -M menuselect '^[[Z' reverse-menu-complete   # Shift-Tab in menus

# Alt-. inserts the last argument of the previous command (default in emacs mode).
# Ctrl-R: history search (replaced by fzf or atuin below when installed).

# ---------------------------------------------------------------------------
# 5. Environment
# ---------------------------------------------------------------------------
export EDITOR=${EDITOR:-nvim}
(( $+commands[$EDITOR] )) || export EDITOR=vi
export VISUAL=$EDITOR
export PAGER=${PAGER:-less}
export LESS='-R -F -i -M'        # colours, quit if one screen, smart case search
export CLICOLOR=1                # coloured ls on macOS/BSD

# ---------------------------------------------------------------------------
# 6. Aliases
# ---------------------------------------------------------------------------
# Navigation
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias -- -='cd -'
alias d='dirs -v | head -10'     # then cd -<number>

# Listing (eza if installed, else ls)
if (( $+commands[eza] )); then
  alias ls='eza --group-directories-first'
  alias ll='eza -l --git --group-directories-first'
  alias la='eza -la --git --group-directories-first'
  alias lt='eza --tree --level=2'
else
  alias ll='ls -lh'
  alias la='ls -lAh'
fi

# Safety
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias mkdir='mkdir -p'

# Git
alias g='git'
alias gs='git status -sb'
alias ga='git add'
alias gap='git add -p'
alias gc='git commit'
alias gcm='git commit -m'
alias gca='git commit --amend --no-edit'
alias gco='git checkout'
alias gsw='git switch'
alias gswc='git switch -c'
alias gd='git diff'
alias gds='git diff --staged'
alias gl='git log --oneline --graph --decorate -20'
alias gla='git log --oneline --graph --decorate --all'
alias gp='git push'
alias gpf='git push --force-with-lease'
alias gpl='git pull --rebase'
alias gst='git stash'
alias gstp='git stash pop'
alias grb='git rebase'
alias gcp='git cherry-pick'

# Tools
alias grep='grep --color=auto'
alias h='history -i 1 | tail -50'      # history with timestamps
alias hg='history -i 1 | grep'         # hg docker
alias path='print -l $path'
alias reload='exec zsh'                # restart the shell cleanly
alias zshrc='${EDITOR} ~/.zshrc'
alias ip4='curl -s https://ifconfig.me; echo'
(( $+commands[bat] )) && alias cat='bat --paging=never --style=plain'
(( $+commands[kubectl] )) && alias k='kubectl'
(( $+commands[docker] )) && alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"'

# Global and suffix aliases (Zsh-only)
alias -g G='| grep -i'          # ps aux G ssh
alias -g L='| less'
alias -g H='| head'
alias -g T='| tail'
alias -g NE='2>/dev/null'
alias -g C='| wc -l'
alias -s {md,txt,json,yaml,yml,toml}=$EDITOR   # typing notes.md opens it

# ---------------------------------------------------------------------------
# 7. Functions (autoloaded from ./functions: loaded on first use)
# ---------------------------------------------------------------------------
if [[ -d $ZSH_PRODUCTIVITY_DIR/functions ]]; then
  fpath=($ZSH_PRODUCTIVITY_DIR/functions $fpath)
  autoload -Uz $ZSH_PRODUCTIVITY_DIR/functions/*(N.:t)
fi

# ---------------------------------------------------------------------------
# 8. Plugins (plain git clones, no framework; see `plug-install` / `plug-update`)
# ---------------------------------------------------------------------------
ZPLUGINS=(
  zsh-users/zsh-completions
  zsh-users/zsh-autosuggestions
  zsh-users/zsh-syntax-highlighting      # must be loaded last
)

plug-install() {
  local repo
  for repo in $ZPLUGINS; do
    [[ -d $ZPLUGDIR/${repo:t} ]] && continue
    git clone --depth 1 "https://github.com/$repo" "$ZPLUGDIR/${repo:t}"
  done
}

plug-update() {
  local dir
  for dir in $ZPLUGDIR/*(N/); do
    print -P "%F{blue}${dir:t}%f"
    git -C $dir pull --ff-only --quiet
  done
  rm -f $ZCACHEDIR/zcompdump*
}

ZSH_AUTOSUGGEST_STRATEGY=(history completion)
ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=20
_zp_source() { [[ -r $1 ]] && source $1 }
_zp_source $ZPLUGDIR/zsh-autosuggestions/zsh-autosuggestions.zsh
bindkey '^ ' autosuggest-accept          # Ctrl-Space accepts the suggestion

# ---------------------------------------------------------------------------
# 9. Tool integrations (each only if installed)
# ---------------------------------------------------------------------------
(( $+commands[fzf] ))    && source <(fzf --zsh 2>/dev/null)          # Ctrl-T files, Ctrl-R history, Alt-C cd
(( $+commands[zoxide] )) && eval "$(zoxide init zsh)"                # z <part of dir>, zi for interactive
(( $+commands[direnv] )) && eval "$(direnv hook zsh)"                # per-folder .envrc
(( $+commands[mise] ))   && eval "$(mise activate zsh)"              # per-project tool versions
(( $+commands[atuin] ))  && eval "$(atuin init zsh --disable-up-arrow)"  # synced, searchable history on Ctrl-R

# ---------------------------------------------------------------------------
# 10. Prompt: Starship if installed, else a small built-in prompt with git info
# ---------------------------------------------------------------------------
if (( $+commands[starship] )); then
  eval "$(starship init zsh)"
else
  autoload -Uz vcs_info add-zsh-hook
  zstyle ':vcs_info:*' enable git
  zstyle ':vcs_info:git:*' check-for-changes true
  zstyle ':vcs_info:git:*' unstagedstr '*'
  zstyle ':vcs_info:git:*' stagedstr '+'
  zstyle ':vcs_info:git:*' formats ' %F{magenta}%b%f%F{yellow}%u%c%f'
  zstyle ':vcs_info:git:*' actionformats ' %F{magenta}%b%f|%F{red}%a%f'
  add-zsh-hook precmd vcs_info

  # Show how long the last command took if it ran for 3+ seconds
  _zp_preexec() { _zp_start=$EPOCHREALTIME }
  _zp_precmd() {
    _zp_took=''
    if [[ -n $_zp_start ]]; then
      local -F elapsed=$(( EPOCHREALTIME - _zp_start ))
      (( elapsed >= 3 )) && _zp_took=" %F{yellow}${elapsed%.*}s%f"
      unset _zp_start
    fi
  }
  zmodload zsh/datetime
  add-zsh-hook preexec _zp_preexec
  add-zsh-hook precmd _zp_precmd

  PROMPT='%F{cyan}%~%f${vcs_info_msg_0_}${_zp_took} %(?.%F{green}.%F{red}[%?] )%#%f '
  RPROMPT='%(1j.%F{blue}%j bg%f.)'
fi

# ---------------------------------------------------------------------------
# 11. Local overrides, then syntax highlighting last
# ---------------------------------------------------------------------------
_zp_source ~/.zshrc.local
_zp_source $ZPLUGDIR/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
unfunction _zp_source
