#!/usr/bin/env bash
# ollie:parallel read
# description: Find files by name/path pattern, sorted by modification time (newest first)
# Args: <pattern> [path]

pattern="$1"
search_path="${2:-$PWD}"

[ -z "$pattern" ] && echo "usage: file_glob <pattern> [path]" && exit 1

if [ ! -d "$search_path" ]; then
    echo "STATUS=error"
    echo "error: path is not a directory: $search_path"
    exit 1
fi

# Collect file matches
if command -v rg >/dev/null 2>&1; then
    file_out=$(rg --no-config --files -g "$pattern" "$search_path" 2>&1)
    rg_exit=$?
    if [ $rg_exit -gt 1 ]; then
        echo "STATUS=error"
        echo "error: $file_out"
        exit 1
    fi
else
    # Fallback: use find with glob pattern
    # Convert glob patterns: **/*.go -> -name '*.go', *.go -> -name '*.go'
    find_pattern="$pattern"
    # Strip leading **/ for find -name compatibility
    find_pattern="${find_pattern##*\*\*/}"
    file_out=$(find "$search_path" -type f -name "$find_pattern" 2>/dev/null)
fi

if [ -z "$file_out" ]; then
    echo "STATUS=no_matches MATCH_COUNT=0"
    echo "no matches"
    exit 0
fi

# Sort by mtime descending
sorted=$(echo "$file_out" \
    | xargs -d '\n' stat --printf '%Y\t%n\n' 2>/dev/null \
    | sort -rn \
    | cut -f2-)

if [ -z "$sorted" ]; then
    # stat failed (e.g. no GNU stat), just output unsorted
    sorted="$file_out"
fi

count=$(echo "$sorted" | wc -l | tr -d ' ')
echo "STATUS=ok MATCH_COUNT=$count"
echo "$sorted"
