#!/usr/bin/env bash

# direct_rofi_ocr.sh - Direct script to 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}/screenshot-gallery/screenshot_ocr.db"

# Check dependencies
check_deps() {
    local missing=0

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

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

    if ! [ -f "$DB_PATH" ]; then
        echo "Error: Database not found at $DB_PATH"
        echo "Please run the OCR script first to create and populate the database."
        missing=1
    fi

    return $missing
}

# Format OCR text (remove newlines, limit length)
format_text() {
    local text="$1"
    text=$(echo "$text" | tr '\n' ' ' | tr -s ' ')

    if [ ${#text} -gt 80 ]; then
        text="${text:0:80}..."
    fi

    echo "$text"
}

# Main function
main() {
    # Check dependencies
    if ! check_deps; then
        exit 1
    fi

    # Create temporary file for mapping
    TEMP_FILE=$(mktemp)
    trap 'rm -f $TEMP_FILE' EXIT

    # Extract data from database
    echo "Querying database..."
    sqlite3 "$DB_PATH" "SELECT filename, full_path, ocr_text FROM ocr_results" | \
    while IFS='|' read -r filename path text; do
        # Format the text for display
        formatted=$(format_text "$text")
        # Write to temp file: display_text|file_path
        echo "$filename | $formatted|$path" >> "$TEMP_FILE"
    done

    # Check if we got any results
    if [ ! -s "$TEMP_FILE" ]; then
        echo "No OCR data found in database. Run ocr_screenshots.py first."
        exit 1
    fi

    # Display in rofi
    echo "Opening rofi dialog..."
    selection=$(cat "$TEMP_FILE" | cut -d'|' -f1-2 | rofi -dmenu -i -p "Screenshot OCR" -width 80)

    # Check if user made a selection
    if [ -z "$selection" ]; then
        echo "No selection made."
        exit 0
    fi

    # Find the corresponding path
    display_text=$(echo "$selection" | sed 's/|.*$//')
    path=$(grep -F "$display_text" "$TEMP_FILE" | cut -d'|' -f3)

    # Open the file
    if [ -n "$path" ] && [ -f "$path" ]; then
        echo "Opening: $path"
        xdg-open "$path" &
    else
        echo "Error: Could not find file path for selection."
        echo "Selected: $display_text"
        echo "Path: $path"
    fi
}

# Run main function
main
