#!/usr/bin/env bash

# simple_rofi_ocr.sh - A simplified script to search OCR'd screenshots with rofi

# Database location
DB_PATH="${XDG_DATA_HOME:-$HOME/.local/share}/orc-gallery/screenshot_ocr.db"

# Check if database exists
if [ ! -f "$DB_PATH" ]; then
    echo "Error: Database not found at $DB_PATH"
    echo "Run the OCR script first to create and populate the database."
    exit 1
fi

# Check if rofi exists
if ! command -v rofi &> /dev/null; then
    echo "Error: rofi is not installed. Please install it with:"
    echo "  sudo pacman -S rofi"
    exit 1
fi

# Check if sqlite3 exists
if ! command -v sqlite3 &> /dev/null; then
    echo "Error: sqlite3 is not installed. Please install it with:"
    echo "  sudo pacman -S sqlite"
    exit 1
fi

# Create a temporary file to store data
TMP_FILE=$(mktemp)
trap 'rm -f $TMP_FILE' EXIT

# Get data from database and format for rofi
sqlite3 -separator '|' "$DB_PATH" "
    SELECT full_path, filename, ocr_text
    FROM ocr_results
    ORDER BY filename
" > "$TMP_FILE"

# Process each line to format for rofi and create menu items
menu_items=""
while IFS='|' read -r path filename ocr_text; do
    # Clean up text for display (replace newlines, truncate)
    clean_text=$(echo "$ocr_text" | tr '\n' ' ' | sed 's/  / /g')
    if [ ${#clean_text} -gt 80 ]; then
        clean_text="${clean_text:0:80}..."
    fi

    # Add to menu items
    menu_items+="$filename | $clean_text\n"
done < "$TMP_FILE"

# Display rofi menu
selection=$(echo -e "$menu_items" | rofi -dmenu -i -p "Screenshot OCR" -width 80 -lines 15 -font "mono 10")

# Exit if no selection
if [ -z "$selection" ]; then
    exit 0
fi

# Extract filename from selection
selected_filename=$(echo "$selection" | cut -d'|' -f1 | sed 's/ *$//')

# Find the path for the selected filename
selected_path=$(grep -F "|$selected_filename|" "$TMP_FILE" | cut -d'|' -f1)

# Open the file if found
if [ -n "$selected_path" ] && [ -f "$selected_path" ]; then
    echo "Opening: $selected_path"
    xdg-open "$selected_path" &
else
    echo "Error: Could not find file: $selected_path"
fi

exit 0
