# vim: set ft=zsh:

function _set_rprompt() {
    local -a _status=("${pipestatus[@]}")
    RPROMPT=""

    # Status code
    if [[ ${#${_status//0/}} -gt 0 ]]; then
        # shellcheck disable=SC2296
        RPROMPT="$RPROMPT %F{red}${(j:|:)_status}%f"
    fi

    # Python virtualenv
    if [[ -n "$VIRTUAL_ENV" ]]; then
        local _venv_name _venv_parent
        local _pyvenv_file="${VIRTUAL_ENV}/pyvenv.cfg"

        if [[ -f "$_pyvenv_file" ]]; then
            while IFS=' = ' read -r key value; do
                if [[ "$key" == "prompt" ]]; then
                    _venv_name="$value"
                    break
                fi
            done <"$_pyvenv_file"
        fi

        _venv_name="${_venv_name:-${VIRTUAL_ENV:t}}"
        _venv_parent="${VIRTUAL_ENV:h:t}"

        if [[ "$_venv_name" == "venv" || "$_venv_name" == ".venv" ]]; then
            _venv_name="$_venv_parent"
        fi

        RPROMPT="$RPROMPT %F{yellow}$_venv_name%f"
    fi

    export RPROMPT
}

export VIRTUAL_ENV_DISABLE_PROMPT=1

# https://zsh.sourceforge.io/Doc/Release/Options.html
setopt PROMPT_BANG
setopt PROMPT_CR
setopt PROMPT_SP
setopt PROMPT_PERCENT
setopt PROMPT_SUBST

# https://zsh.sourceforge.io/Doc/Release/Parameters.html
# https://zsh.sourceforge.io/Doc/Release/Prompt-Expansion.html
PROMPT='%(#.%F{red}.%12F)%n@%m%f %1~ %(#.#.$) '
PROMPT_START=$'%{\e]133;A\a%}'
PROMPT_END=$'%{\e]133;B\a%}'
export PROMPT=${PROMPT_START}${PROMPT}${PROMPT_END}
export PROMPT2="> "

# https://zsh.sourceforge.io/Doc/Release/Functions.html#Hook-Functions
typeset -a precmd_functions
precmd_functions+=(_set_rprompt)
