#!/usr/bin/env zsh
#
# zrgf - fzf + fd to interactively search for files - with reload

emulate -LR zsh
setopt extendedglob warncreateglobal

local MATCH; integer MEND MBEGIN
local -a match=() mbegin=() mend=()
local FD_PREFIX INITIAL_QUERY
local res action
local -a fd_filtered f_filtered fd_cmd
local -a opts

#  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# -s, --case-sensitive   A case-sensitive search
# -i, --ignore-case      A case-insensitive search
# -g, --glob             A glob-based search instead of a regular expression search
# --regex                A regular-expression based search (default)
# -F, --fixed-strings    Treat pattern as a literal string instead of a regular expression
# -H, --hidden           Include hidden files and directories
# -I, --no-ignore        Don't respect: [.gitignore, .git/info/exclude, git/ignore, .ignore, .fdignore, fd/ignore]
# -u, --unrestricted     Unrestricted search, alias for '--hidden --no-ignore'
# -a, --absolute-path    Show full path starting from the root as opposed to relative paths

zmodload -Fa zsh/zutil b:zparseopts
zparseopts -E -F -D -a opts - \
    x -show-error \
    \? -debug \
    / -cd \
    1 -print \
    X -execute \
    {e,-ext}+:- \
    {E,-exclude}+:- \
    {t,-type}+:- \
    {S,-size}+:- \
    {o,-owner}+:- \
    {O,-older}:- \
    {N,-newer}:- \
    {d,-max-depth}:- \
    {D,-min-depth}:- \
    {R,-max-results}:- \
    {T,-search-path}+:- \
    g -glob \
    G -regex \
    L -follow \
    l -no-follow \
    I -ignore \
    n -no-ignore \
    H -no-hidden \
    u -unrestricted \
    p -prune \
    s -sensitive \
    F -fixed \
    a -absolute \
    A -relative \
    {h,-height}:- \
    {b,-bind}+:- \
    {Z,-preview-size}:- \
       -delimiter:- \
    {w,-with-nth}:- \
    P -no-preview \
    m -multi

integer preview_size
preview_size=${${${(M)opts:#-(Z|-preview-size)(=|)(#b)([0-9]##)}//*/$match[1]}:-60}

action='enter:accept'
if (( ! (($+opts[(r)-1]+$+opts[(r)--print]) || ($+opts[(r)-/]+$+opts[(r)--cd])) )); then
  local ex="become"
  (( $+opts[(r)-X]+$+opts[(r)--execute] )) && ex="execute"
  action="enter:$ex($EDITOR {} </dev/tty >/dev/tty)"
fi

fd_filtered=(
  ${${${(M@)opts:#-(e|-ext(=|))*}##-(e|-ext(=|))}//(#m)*/--extension=${(q-)MATCH}}
  ${${${(M@)opts:#-(E|-exlude(=|))*}##-(e|-exlude(=|))}//(#m)*/--exlude=${(q-)MATCH}}
  ${${${(M@)opts:#-(t|-type(=|))*}##-(t|-type(=|))}//(#m)*/--type=${(q-)MATCH}}
  ${${${(M@)opts:#-(o|-owner(=|))*}##-(o|-owner(=|))}//(#m)*/--owner=${(q-)MATCH}}
  ${${${(M@)opts:#-(S|-size(=|))*}##-(S|-size(=|))}//(#m)*/--size=${(q-)MATCH}}
  ${${${(M@)opts:#-(O|-older(=|))*}##-(O|-older(=|))}//(#m)*/--older=${(q-)MATCH}}
  ${${${(M@)opts:#-(N|-newer(=|))*}##-(N|-newer(=|))}//(#m)*/--newer=${(q-)MATCH}}
  ${${${(M@)opts:#-(d|-max-depth(=|))*}##-(d|-max-depth(=|))}//(#m)*/--max-depth=${(q-)MATCH}}
  ${${${(M@)opts:#-(D|-min-depth(=|))*}##-(D|-min-depth(=|))}//(#m)*/--min-depth=${(q-)MATCH}}
  ${${${(M@)opts:#-(R|-max-results(=|))*}##-(R|-max-results(=|))}//(#m)*/--max-results=${(q-)MATCH}}
  ${${${(M@)opts:#-(T|-search-path(=|))*}##-(T|-search-path(=|))}//(#m)*/--search-path=${(q-)MATCH}}

  ${${${(M)${+opts[(r)-(g|-glob)]}:#1}:+--glob}:-}
  ${${${(M)${+opts[(r)-(G|-regex)]}:#1}:+--regex}:-}
  ${${${(M)${+opts[(r)-(p|-prune)]}:#1}:+--prune}:-}
  ${${${(M)${+opts[(r)-(s|-sensitive)]}:#1}:+--case-sensitive}:-}
  ${${${(M)${+opts[(r)-(F|-fixed)]}:#1}:+--fixed-strings}:-}
  ${${${(M)${+opts[(r)-(a|-absolute)]}:#1}:+--absolute-path}:-}
  ${${${(M)${+opts[(r)-(A|-relative)]}:#1}:+--relative-path}:-}

  ${${${(M)${+opts[(r)-(I|-ignore)]}:#1}:+--ignore}:-}
  ${${${(M)${+opts[(r)-(L|-follow)]}:#1}:+--follow}:-}

  ${${${(M)${+opts[(r)-(n|-no-ignore)]}:#1}:+--no-ignore}:-}
  ${${${(M)${+opts[(r)-(f|-no-follow)]}:#1}:+--no-follow}:-}
  ${${${(M)${+opts[(r)-(H|-no-hidden)]}:#1}:+--no-hidden}:-}
  ${${${(M)${+opts[(r)-(u|-unrestricted)]}:#1}:+--unrestricted}:-}
)

f_filtered=(
  ${${${(M@)opts:#-(h|-height(=|))*}##-(h|-height(=|))}//(#m)*/--height=${(q)MATCH}}
  ${${${(M@)opts:#-(b|-bind(=|))*}##-(b|-bind(=|))}//(#m)*/--bind=${(q-)MATCH}}
  ${${${(M@)opts:#-(w|-with-nth(=|))*}##-(w|-with-nth(=|))}//(#m)*/--with-nth=${(q-)MATCH}}
  ${${${(M@)opts:#--delimiter(=|)*}##--delimiter(=|)}//(#m)*/--delimiter=${(q-)MATCH}}

  ${${${(M)${+opts[(r)-(m|-multi)]}:#1}:+--multi}:-}
)

fd_cmd=(
  command fd
  --hidden --ignore-case --follow --color=always
  ${(j: :)fd_filtered}
)
FD_PREFIX="${(j: :)fd_cmd}"
INITIAL_QUERY="${*:-}"
FZF_DEFAULT_COMMAND="$FD_PREFIX ${(q)INITIAL_QUERY} ${${${(M)${+opts[(r)-(x|-show-error)]}:#0}:+|| true}:-}"

if (($+opts[(r)--debug] + $+opts[(r)-\?])); then
  local nlt=$'\n\t'
  print -x4  -- "OPTIONS: ${opts[@]:+$nlt${(pj:$nlt:)opts[@]}}"
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -rx4 -- "FD COMMAND: " ${fd_cmd[@]:+$'\n\t'${(pj:\n\t\t:)fd_cmd[@]}}" "
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -x4  -- "FD OPTS: ${fd_filtered[@]:+$nlt${(pj:$nlt:)fd_filtered[@]}}"
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -x4  -- "PREFIX (RELOAD): ${FD_PREFIX:+$nlt$FD_PREFIX}"
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -x4  -- "QUERY: ${INITIAL_QUERY:+$nlt$INITIAL_QUERY}"
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -x4  -- "FZF OPTS: ${f_filtered[@]:+$nlt${(pj:$nlt:)f_filtered[@]}}"
  print -r   -- "${(l:COLUMNS::=:):-}"
  print -x4  -- "FZF_DEFAULT_COMMAND: ${FZF_DEFAULT_COMMAND:+$nlt$FZF_DEFAULT_COMMAND}"
  return 0
fi

res=$(fzf  \
    --ansi \
    --cycle \
    --exit-0 \
    --bind="focus:transform-border-label:echo [ {} ]" \
    --bind="$action" \
    --bind='ctrl-e:execute($EDITOR {})' \
    --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)+abort" \
    --preview='([[ -f {} ]] && (bat --style=changes,numbers,snip --color=always {})) \
        || ([[ -d {} ]] && (eza -TL 3 --color=always --icons {} | less)) \
        || echo {} 2> /dev/null | head -200' \
    --preview-window="default:right:${preview_size}%:+{2}+3/2:border-left${${${(M)${+opts[(r)-(P|-no-preview)]}:#1}:+:hidden}:-}" \
    ${(z)${(j: :)f_filtered}}
)

if [[ -z "$res" ]]; then
  zle && zle redisplay
  return 0
fi

res="$res:A"
if [[ -n "$res" ]] {
  if (( $+opts[(r)-1]+$+opts[(r)--print] )); then
    print -r -- "$res"
  elif (( $+opts[(r)-/]+$+opts[(r)--cd] )); then
    [[ ! -d "$res" ]] && res="$res:h"
    builtin cd "$res"
  else
    $EDITOR "$res"
  fi
}

