# Powerlevel10k instant prompt and machine-local layers must remain first.
[[ -f ~/.zsh/.powerline_config ]] && source ~/.zsh/.powerline_config
[[ -f ~/.zsh/.user_config ]] && source ~/.zsh/.user_config
[[ -f ~/.zsh/.virtual_env_config.zsh ]] && source ~/.zsh/.virtual_env_config.zsh
[[ -f ~/.zsh/.local_config ]] && source ~/.zsh/.local_config

source "${ZDOTDIR:-$HOME}/.zsh/lib/updates.zsh"
export LC_OSC52=1

plugins_txt=${ZDOTDIR:-$HOME}/.zsh/.zsh_plugins.txt
static_file=${ZDOTDIR:-$HOME}/.cache/zsh/.zsh_plugins.zsh
source "${ZDOTDIR:-$HOME}/.zsh/lib/antidote.zsh"
source "${ZDOTDIR:-$HOME}/.zsh/lib/interactive.zsh"

bindkey '^w' kill-region
bindkey -v
VI_MODE_SET_CURSOR=true

[[ -f ~/.zsh/.mac_config.zsh ]] && source ~/.zsh/.mac_config.zsh
if (( $+commands[go] )); then
    export GOPATH="$(go env GOPATH 2>/dev/null)"
    [[ -n "$GOPATH" ]] && path+=("$GOPATH/bin")
fi

# Use safe wrappers after ~/.local/bin has been added to PATH.
(( $+commands[safecp] )) && alias cp=safecp
(( $+commands[safemv] )) && alias mv=safemv
(( $+commands[safescp] )) && alias scp=safescp

if [[ -f ~/.ssh/sudo_key ]]; then
    [[ -e /tmp/sudo-agent.sock ]] || ssh-agent -a /tmp/sudo-agent.sock &>/dev/null
    SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add -l |
        grep -q "$(ssh-keygen -lf ~/.ssh/sudo_key | awk '{print $2}')" ||
        SSH_AUTH_SOCK=/tmp/sudo-agent.sock ssh-add ~/.ssh/sudo_key
fi
export SUDO_ASKPASS=$(command -v ssh-askpass)

if [[ -f ~/dotfiles/zsh/.p10k.mac.zsh ]]; then
    p10k_config=~/dotfiles/zsh/.p10k.mac.zsh
else
    p10k_config=~/dotfiles/zsh/.p10k.zsh
fi
source "${ZDOTDIR:-$HOME}/.zsh/lib/prompt.zsh"

alias screenshot_mode='powerlevel10k_plugin_unload; export PS1="$ "; python3 ~/.config/alacritty/screenshot_mode.py on'
alias screenshot_mode_off='prompt_powerlevel9k_setup; python3 ~/.config/alacritty/screenshot_mode.py off'
antidote update &>/dev/null &|

[[ -d "$HOME/.lmstudio/bin" ]] && path+=("$HOME/.lmstudio/bin")
[[ -d "$HOME/.runai/bin" ]] && path+=("$HOME/.runai/bin")
runai_bin="$HOME/.runai/bin/runai"
runai_completion=${ZDOTDIR:-$HOME}/.cache/zsh/runai-completion.zsh
if [[ -x "$runai_bin" ]]; then
    if [[ ! -s "$runai_completion" || "$runai_bin" -nt "$runai_completion" ]]; then
        runai_completion_tmp="$runai_completion.$$.tmp"
        if "$runai_bin" --quiet completion zsh >| "$runai_completion_tmp"; then
            command mv -f "$runai_completion_tmp" "$runai_completion"
        else
            command rm -f "$runai_completion_tmp"
        fi
    fi
    [[ -s "$runai_completion" ]] && source "$runai_completion"
fi

# Keep this last: activate must snapshot the fully built PATH for deactivate.
typeset -U path PATH
[[ -z "${VIRTUAL_ENV:-}" ]] && unset VIRTUAL_ENV
if [[ -n "$VIRTUAL_ENV" && -f "$VIRTUAL_ENV/bin/activate" ]]; then
    if [[ ":$PATH:" != *":$VIRTUAL_ENV/bin:"* ]]; then
        source "$VIRTUAL_ENV/bin/activate"
    fi
fi
