# Shared PATH setup for local shells.
# Source this from login and interactive startup files; it is idempotent.

_pathrc_path_has() {
    case ":${PATH:-}:" in
        *:"$1":*) return 0 ;;
        *) return 1 ;;
    esac
}

_pathrc_path_remove() {
    [ -n "${PATH:-}" ] || return 0

    _pathrc_old_ifs=$IFS
    IFS=:
    _pathrc_new_path=
    for _pathrc_dir in $PATH; do
        [ "$_pathrc_dir" = "$1" ] && continue
        [ -n "$_pathrc_dir" ] || continue
        case ":$_pathrc_new_path:" in
            *:"$_pathrc_dir":*) ;;
            *)
                if [ -n "$_pathrc_new_path" ]; then
                    _pathrc_new_path="$_pathrc_new_path:$_pathrc_dir"
                else
                    _pathrc_new_path="$_pathrc_dir"
                fi
                ;;
        esac
    done
    IFS=$_pathrc_old_ifs
    PATH=$_pathrc_new_path
}

_pathrc_path_prepend() {
    [ -d "$1" ] || return 0
    _pathrc_path_remove "$1"

    if [ -n "${PATH:-}" ]; then
        PATH="$1:$PATH"
    else
        PATH="$1"
    fi
}

_pathrc_path_append() {
    [ -d "$1" ] || return 0
    _pathrc_path_has "$1" && return 0

    if [ -n "${PATH:-}" ]; then
        PATH="$PATH:$1"
    else
        PATH="$1"
    fi
}

if [ -d /opt/homebrew ]; then
    export HOMEBREW_PREFIX=/opt/homebrew
    export HOMEBREW_CELLAR=/opt/homebrew/Cellar
    export HOMEBREW_REPOSITORY=/opt/homebrew
fi

export GEM_HOME="$HOME/.gem"
export NVM_DIR="$HOME/.nvm"
export ASDF_DATA_DIR="${ASDF_DATA_DIR:-$HOME/.asdf}"

# Prepend in reverse priority order.
_pathrc_path_prepend "$HOME/Documents/codex-tools/mcpgw-cli"
_pathrc_path_prepend "$HOME/.fzf/bin"
_pathrc_path_prepend "$HOME/.rd/bin"
_pathrc_path_prepend "$HOME/work/flutter/bin"
_pathrc_path_prepend "$HOME/bin"
_pathrc_path_prepend "$HOME/.local/bin"
_pathrc_path_prepend /usr/local/bin
_pathrc_path_prepend "$ASDF_DATA_DIR/shims"
_pathrc_path_prepend /opt/homebrew/sbin
_pathrc_path_prepend /opt/homebrew/bin
_pathrc_path_prepend /opt/homebrew/opt/ruby/bin
_pathrc_path_prepend "$HOME/.gem/ruby/3.3.0/bin"
_pathrc_path_prepend "$GEM_HOME/bin"

_pathrc_path_append /usr/bin
_pathrc_path_append /bin
_pathrc_path_append /usr/sbin
_pathrc_path_append /sbin

if [ -n "${ZSH_VERSION:-}" ] && [ -d /opt/homebrew/share/zsh/site-functions ]; then
    fpath=(/opt/homebrew/share/zsh/site-functions ${fpath:#/opt/homebrew/share/zsh/site-functions})
fi

if [ -d /opt/homebrew/share/info ]; then
    case ":${INFOPATH:-}:" in
        *:/opt/homebrew/share/info:*) ;;
        *) export INFOPATH="/opt/homebrew/share/info:${INFOPATH:-}" ;;
    esac
fi

export PATH

unset -f _pathrc_path_has _pathrc_path_remove _pathrc_path_prepend _pathrc_path_append 2>/dev/null || true
unset _pathrc_old_ifs _pathrc_new_path _pathrc_dir
