#!/bin/sh
# Fuzzy find and execute a Fabric pattern.
json_file=$HOME/.config/fabric/pattern_explainations.json

if [ ! -f "$json_file" ]; then
    printf '\033[31mError: %s not found.\033[0m\n' "$json_file" >&2
    exit 1
fi

# fabric is aliased to fabric-ai in the shells; resolve the real binary here
if command -v fabric-ai >/dev/null 2>&1; then
    fabric_bin=fabric-ai
else
    fabric_bin=fabric
fi

# 1. Safely capture piped input (if any) to a temp file — preserves all
#    formatting and newlines, avoids variable escaping issues
temp_input=$(mktemp)
trap 'rm -f "$temp_input"' EXIT INT TERM

if [ ! -t 0 ]; then
    cat > "$temp_input"
fi

# 2. Parse JSON to TSV -> fzf (name in list, description in preview)
selection=$(jq -r '.[] | "\(.name)\t\(.description)"' "$json_file" \
    | fzf --delimiter '\t' \
          --with-nth 1 \
          --preview 'echo {2}' \
          --preview-window 'right:60%:wrap' \
          --prompt 'Pattern > ' \
          --info inline \
          --bind 'ctrl-/:toggle-preview')

# 3. Execute with or without the piped data
if [ -n "$selection" ]; then
    pattern=$(printf '%s\n' "$selection" | cut -f1)
    if [ -s "$temp_input" ]; then
        "$fabric_bin" --pattern "$pattern" < "$temp_input"
    else
        "$fabric_bin" --pattern "$pattern"
    fi
fi
