#!/usr/bin/env bash
# ollie:parallel read
# description: Search files using Baloo (KDE file indexer). Args: <query> [--type=document|image|video|audio] [--path=dir] [--limit=n]
set -euo pipefail

query="${1:?usage: gui_files <query> [--type=TYPE] [--path=DIR] [--limit=N]}"
shift

# Parse flags
file_type=""
path_filter=""
limit="50"

while [ $# -gt 0 ]; do
    case "$1" in
        --type=*) file_type="${1#--type=}" ;;
        --path=*) path_filter="${1#--path=}" ;;
        --limit=*) limit="${1#--limit=}" ;;
        *) ;;
    esac
    shift
done

# Build baloosearch command
cmd=(baloosearch)

# Add type filter
case "$file_type" in
    document|doc) cmd+=(-t Document) ;;
    image|img)    cmd+=(-t Image) ;;
    video|vid)    cmd+=(-t Video) ;;
    audio|snd)    cmd+=(-t Audio) ;;
    folder|dir)   cmd+=(-t Folder) ;;
    "")
        ;;
    *)
        cmd+=(-t "$file_type")
        ;;
esac

# Add path filter
if [ -n "$path_filter" ]; then
    cmd+=(-d "$path_filter")
fi

# Add limit
cmd+=(-l "$limit")

# Add query
cmd+=("$query")

# Try baloosearch first
if command -v baloosearch &>/dev/null; then
    "${cmd[@]}" 2>/dev/null
    exit $?
fi

# Fallback: try baloosearch6
if command -v baloosearch6 &>/dev/null; then
    cmd[0]="baloosearch6"
    "${cmd[@]}" 2>/dev/null
    exit $?
fi

# Fallback: D-Bus query to Baloo
if gdbus introspect --session --dest org.kde.baloo --object-path /org/kde/baloo &>/dev/null 2>&1; then
    result=$(gdbus call --session \
        --dest org.kde.baloo \
        --object-path /org/kde/baloo \
        --method org.kde.baloo.main.search "$query" "$limit" 2>/dev/null)
    echo "$result" | sed "s/^(\[//;s/\],)$//;s/'//g;s/, /\n/g"
    exit 0
fi

# Last fallback: locate
if command -v locate &>/dev/null; then
    echo "# (using locate fallback - results may be stale)" >&2
    locate -i "$query" | head -n "$limit"
    exit 0
fi

echo "ERROR: Baloo not available and no fallback found (install baloo-utils or mlocate)" >&2
exit 1
