# Tmux on SSH (https://stackoverflow.com/a/40192494)
if [[ $- =~ i ]] && [[ -z "$TMUX" ]] && [[ -n "$SSH_TTY" ]]; then
  systemd-inhibit --what=sleep --why="SSH session connected in tmux" sh -c 'tmux attach-session -t ssh || tmux new-session -s ssh'
  exit # close the shell if tmux is detached/closed
fi

export GPG_TTY=$TTY

# p10k instant prompt
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

# Custom completions path
fpath=("$HOME/.config/zsh/completions" $fpath)

# source zsh-autocomplete
source $ZSH_CUSTOM/plugins/zsh-autocomplete/zsh-autocomplete.plugin.zsh

##### omz configuration #####

# Theme (p10k)
ZSH_THEME="powerlevel10k/powerlevel10k"

# Disable automatic updates
zstyle ':omz:update' mode disabled

# Show loading prompt
COMPLETION_WAITING_DOTS=false

# Case insensitive match
CASE_SENSITIVE=false

# Use hyphen and underscore interchangably
HYPHEN_INSENSITIVE=true

# Pasting urls magic functions
DISABLE_MAGIC_FUNCTIONS=false

# Command correction
ENABLE_CORRECTION=true

# Mark untracked files as dirty (for speed in large repositories)
# DISABLE_UNTRACKED_FILES_DIRTY=true

# History
HIST_STAMPS="yyyy-mm-dd"

# Set vim mode
# set -o vi
# bindkey -v '^?' backward-delete-char

## zsh configuration

setopt HIST_IGNORE_ALL_DUPS

##### END omz configuration #####

##### omz plugins configuration #####
plugins=()

# als command to view aliases
plugins+=(aliases)

# Show when shortcuts are available
# plugins+=(alias-finder)
zstyle ':omz:plugins:alias-finder' autoload yes
zstyle ':omz:plugins:alias-finder' longer no
zstyle ':omz:plugins:alias-finder' exact no
zstyle ':omz:plugins:alias-finder' cheaper yes

# Notify when background jobs finish
plugins+=(bgnotify)
bgnotify_bell=true
bgnotify_threshold=300
bgnotify_extraargs="-a zsh -u low"
function bgnotify_formatted {
  ## $1=exit_status, $2=command, $3=elapsed_time

  local ignore=(
    "lazygit"
    "nvim"
    "vim"
    "nano"
    "less"
    "man"
    "more"
    "yt-x"
    "fastanime"
    "btop"
    "htop"
    "top"
    "iotop"
    "battop"
    "nvimconf"
    "zshconf"
    "zsh"
    "bash"
    "sh"
    "isd"
    "journalctl"
    "systemctl-tui"
    "watch"
    "python"
    "python3"
    "tmux"
    "sleep"
    "mpv"
    "ytfzf"
    "ssh"
    "topgrade"
  )

  program=$(echo $2 | awk '{print $1}')

  if [[ "${ignore[@]}" =~ "$program" ]]; then
    return
  fi

  # Humanly readable elapsed time
  local elapsed="$(( $3 % 60 ))s"
  (( $3 < 60 ))   || elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
  (( $3 < 3600 )) || elapsed="$((  $3 / 3600 ))h $elapsed"

  if [[ $1 -eq 0 ]]; then
    local bg_status="completed"
  else
    local bg_status="failed"
  fi

  bgnotify "$program ${bg_status} - took ${elapsed} - $2"
}

# pkgfile command-not-found
plugins+=(command-not-found)

# Use <C-o> to copy current command to clipboard
plugins+=(copybuffer)

# direnv
plugins+=(direnv)

# eza
# plugins+=(eza)
zstyle ':omz:plugins:eza' 'git-status' yes
zstyle ':omz:plugins:eza' 'show-group' no
zstyle ':omz:plugins:eza' 'size-prefix' binary

# Use <C-z> to fg suspended job
plugins+=(fancy-ctrl-z)

# Git
plugins+=(git git-auto-fetch forgit ugit)
export FORGIT_FZF_DEFAULT_OPTS="--exact --cycle --border --reverse"

# Use <ESC>+man or <ESC>+tldr to see prev command help
plugins+=(man tldr)

# Prevent running pasted commands
plugins+=(safe-paste)

# Use <ESC><ESC> to prefix command with sudo
# plugins+=(sudo)

# ufw completion
plugins+=(ufw)

# Archive utilities
plugins+=(extract universalarchive)

# Auto activate python virtualenv
plugins+=(virtualenvwrapper)

# Z
plugins+=(z)

# Alias reminder (alias-finder alternative)
# plugins+=(zsh-you-should-use)
YSU_MESSAGE_FORMAT="$(tput setaf 211)%command$(tput sgr0) $(tput setaf 221)->$(tput sgr0) $(tput setaf 151)%alias$(tput sgr0)"

#### END omz plugins configuration #####


#### command wrappers ####

# App wrapper pipeline — each block maps apps to wrappers
# Wrappers are applied inner-to-outer (first registered = innermost)
typeset -gA _app_wrappers=()

__app-dispatch() {
  local app=$1; shift
  local bin
  bin=$(whence -p "$app") || { echo "command not found: $app" >&2; return 127 }

  (( $+compstate )) && { "$bin" "$@"; return }

  local -a _wrap_cmd=("$bin" "$@")
  local _wrapper
  for _wrapper in ${=_app_wrappers[$app]}; do
    "__${_wrapper}-apply" "$app"
  done
  "${_wrap_cmd[@]}"
}

# Systemd-inhibit wrapper
inhibit_apps=(claude copilot codex cp mv rsync mov copy topgrade lftp aria2c crush pi)

systemd-inhibit --what=sleep --why=probe true 2>/dev/null && _inhibit_ok=1
__inhibit-apply() {
  [[ -n $_inhibit_ok ]] || return
  _wrap_cmd=(systemd-inhibit --what=sleep --why="$1 - automated zsh hook action" "${_wrap_cmd[@]}")
}

for _app in $inhibit_apps; do _app_wrappers[$_app]+="inhibit "; done
unset _app

# Tmux wrapper
tmux_apps=(claude copilot codex crush pi aria2c lftp)

__tmux-apply() {
  if [[ -z "$TMUX" ]]; then
    local _sess="$1-$(basename "$PWD")"
    _wrap_cmd=(tmux new-session -A -s "$_sess" -- "${_wrap_cmd[@]}")
  fi
}

for _app in $tmux_apps; do _app_wrappers[$_app]+="tmux "; done
unset _app

# Generate wrapper functions for all registered apps
for _app in ${(k)_app_wrappers}; do
  eval "function $_app() { __app-dispatch $_app \"\$@\" }"
done
unset _app


#### END command wrappers ####

# LS_COLORS
export LS_COLORS="$(vivid generate catppuccin-mocha)"

# Sourcing
source $ZSH/oh-my-zsh.sh
source <(fzf --zsh) # fzf history
source $ZSH_CUSTOM/themes/zsh-syntax-highlighting/themes/catppuccin_mocha-zsh-syntax-highlighting.zsh
source $ZSH_CUSTOM/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh
source $ZDOTDIR/zshalias

##### zsh configuration #####

HISTSIZE=100000
SAVEHIST=100000
setopt INC_APPEND_HISTORY

##### END zsh configuration #####

##### unalias commands #####

unalias cp
unalias mv

##### END unalias commands #####

##### zsh-autocomplete configuration #####

zstyle ':completion:*' completer _complete _complete:-fuzzy _correct _approximate _ignored
zstyle ':autocomplete:*' delay 0.2

# Make Tab and ShiftTab go to the menu
bindkey '^I' menu-select
bindkey "$terminfo[kcbt]" menu-select

# # Make Tab and ShiftTab change the selection in the menu
# bindkey -M menuselect '^I' menu-complete
# bindkey -M menuselect "$terminfo[kcbt]" reverse-menu-complete

bindkey '^[OA' history-search-backward

##### END zsh-autocomplete configuration #####

# Hyprland splash
if [[ $XDG_SESSION_DESKTOP == "Hyprland" && $TERM == "alacritty" ]]; then echo "$(hyprctl splash | lolcat -f &)"; fi

# Initialize p10k prompt
[[ ! -f ${ZDOTDIR:-~}/.p10k.zsh ]] || source ${ZDOTDIR:-~}/.p10k.zsh

