#!/usr/bin/env zsh

# read function from $ZDOTDIR/functions

_wh() {
  for thing in "$@"; do
    case $(where "${thing}") in
      *'builtin autoload'*)
        autoload +X "${thing}"
        echo "# note: ${thing} was autoloaded"
        ;;
      *)
        return 1
        ;;
    esac
  done
  where "$@"
}

emulate -L zsh
setopt local_options extended_glob rc_expand_param

funcs=(${fpath}/$1(N))

if [ "${#funcs}" -gt 0 ]; then
  command bat --color=always --language=sh --style=header-filename "$funcs[2]"
else
  # file=$(readlink -f "$(command -v "$1")")
  funcfile=$(type "$1" | awk "{print \$7}")
  echo "$(type "$1" | awk "{print \$7}" | cut -d / -f5-)"
  printf "\n"
  # command cat $(type "$1" | field 7) | rg --color=never --before-context=1 --glob-case-insensitive --after-context=0 "$1" | rg --color=never --regexp="(#|@|dependencies:)"
  command bat --color=always --theme=ansi "${funcfile}" | rg --before-context=1 --glob-case-insensitive --after-context=0 "$1" | rg --color=never --regexp="(#|@|dependencies:)"
  printf "\n"
  _wh "$1" | command bat --style=snip --language=sh --pager=never
fi
