#compdef penv

_autoload_penv() {
  venv_file=".pyenv"

  if [ -n "${PENV_VENV}" ]; then
    return
  fi

  if [ -f "${venv_file}" ]; then
    venv_name=$(<"${venv_file}")
    venv_dir="$HOME/.local/share/pyenv/${venv_name}"

    if [ -d "${venv_dir}" ]; then
      if [ "${VIRTUAL_ENV}" != "${venv_dir}" ]; then
        source "${venv_dir}/bin/activate"
        echo "Auto-activated virtual environment: ${venv_name}"
      fi
      return
    fi
  fi

  if [ -n "${VIRTUAL_ENV}" ]; then
    deactivate
    echo "Deactivated virtual environment because no .pyenv file was found in the current directory."
  fi
}
autoload -U add-zsh-hook
add-zsh-hook chpwd _autoload_penv

# _autoload_penv
_penv() {
  local -a subcommands
  subcommands=(
    "list:List all available virtual environments"
    "create:Create a new virtual environment"
    "delete:Delete an existing virtual environment"
    "shell:Set a virtual environment for the current shell session, or unset it with --unset"
    "local:Set a virtual environment for the current directory, or unset it with --unset"
    "why:Explain why a virtual environment is active (or not)"
    "w:Alias for 'penv why'"
    "l:Alias for 'penv list'"
  )

  local -a venv_names
  if [[ $words[2] =~ ^(delete|shell|local)$ ]]; then
    local venv_dir="${HOME}/.local/share/pyenv"
    if [[ -d "${venv_dir}" ]]; then
      venv_names=("${(f)$(ls -1 $venv_dir)}")
    else
      venv_names=()
    fi

    [[ $words[2] =~ ^(shell|local)$ ]] && venv_names+=("--unset")
  fi

  if (( CURRENT == 2 )); then
    _describe -t commands "penv subcommands" subcommands
  elif (( CURRENT == 3 )); then
    _describe -t venvs "Available virtual environments" venv_names
  fi
}
compdef _penv penv
