#!/bin/bash

# ocr_rofi.sh - Search OCR'd screenshots with rofi
# This script displays OCR data from SQLite and allows opening files with rofi

# Database path
DB_PATH="${XDG_DATA_HOME:-$HOME/.local/share}/orc-gallery/screenshot_ocr.db"
SCREENSHOTS_DIR="$HOME/Screenshots"
MAX_TEXT_LENGTH=100

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

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

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

# Create temporary files
ENTRIES_FILE=$(mktemp)
PATHS_FILE=$(mktemp)
trap "rm -f $ENTRIES_FILE $PATHS_FILE" EXIT

# Query the database and format for rofi
echo "Preparing OCR data for search..."
sqlite3 -separator "|" "$DB_PATH" "SELECT filename, ocr_text, full_path FROM ocr_results ORDER BY filename" | while IFS="|" read -r filename ocr_text path; do
    # Clean up text (remove newlines, limit length)
    clean_text=$(echo "$ocr_text" | tr '\n' ' ' | tr -s ' ')
    if [ ${#clean_text} -gt $MAX_TEXT_LENGTH ]; then
        clean_text="${clean_text:0:$MAX_TEXT_LENGTH}..."
    fi

    # Save formatted entry for rofi
    echo "$filename | $clean_text" >> "$ENTRIES_FILE"

    # Save path in corresponding line
    echo "$path" >> "$PATHS_FILE"
done

# Count entries
entry_count=$(wc -l < "$ENTRIES_FILE")
if [ "$entry_count" -eq 0 ]; then
    echo "No OCR data found in database. Run ocr_screenshots.py first."
    exit 1
fi

echo "Found $entry_count screenshots with OCR data."

# Display rofi menu
selected_line=$(cat "$ENTRIES_FILE" | rofi -dmenu -i -p "Screenshot OCR" \
    -width 80 -lines 15 -font "mono 10")

# Exit if no selection
if [ -z "$selected_line" ]; then
    echo "No selection made."
    exit 0
fi

# Get filename from selection
selected_filename=$(echo "$selected_line" | cut -d '|' -f 1 | sed 's/ *$//')

# Find corresponding line number
line_num=1
while IFS= read -r line; do
    if [[ "$line" == "$selected_filename"* ]]; then
        break
    fi
    line_num=$((line_num + 1))
done < "$ENTRIES_FILE"

# Get full path from paths file
selected_path=$(sed "${line_num}q;d" "$PATHS_FILE")

# Open the file
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"
    exit 1
fi

exit 0
