#!/usr/bin/env bash
# ollie:parallel read
# args_json: {"type":"object","required":["pattern"],"properties":{"pattern":{"type":"string","description":"Glob pattern (e.g. \"*.go\", \"**/*.ts\")"},"search_dir":{"type":"string","description":"Absolute search directory path (optional, defaults to cwd)"}}}
# ollie:prompt
# ## file_glob
#
# Find files by glob pattern, sorted by mtime (newest first).
#
# **Args**: `[pattern]` or `[pattern, search_dir]`
#
# - First arg: glob pattern (e.g. `"*.go"`, `"**/*.ts"`).
# - Second arg (optional): absolute search directory. Defaults to cwd.
#
# ```
# file_glob(pattern="*.go", search_dir="/abs/search/dir")
# file_glob(pattern="**/*.go")
# ```
# ollie:end

source "$(dirname "$0")/_lib/args.sh"

pattern=$(arg_require "pattern")
search_path=$(arg_get "search_dir" "$PWD")

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
    find_pattern="$pattern"
    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
    sorted="$file_out"
fi

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