#!/bin/bash

# OCR screenshot images and store results in SQLite database
# This script is a wrapper for the ocr_screenshots.py Python script

# Set up variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_SCRIPT="${SCRIPT_DIR}/ocr_screenshots.py"
DATABASE_PATH="$HOME/screenshot_ocr.db"
SCREENSHOTS_DIR="$HOME/Screenshots"

# Check if Python script exists
if [ ! -f "$PYTHON_SCRIPT" ]; then
    echo "Error: Python script not found at $PYTHON_SCRIPT"
    exit 1
fi

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

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

# Check if screenshots directory exists
if [ ! -d "$SCREENSHOTS_DIR" ]; then
    echo "Error: Screenshots directory not found at $SCREENSHOTS_DIR"
    exit 1
fi

echo "Starting OCR process for screenshots..."
echo "Database path: $DATABASE_PATH"
echo "Screenshots directory: $SCREENSHOTS_DIR"

# Run the Python script
python "$PYTHON_SCRIPT"

# Check return code
if [ $? -ne 0 ]; then
    echo "Error: OCR process failed"
    exit 1
else
    # Count entries in database
    if [ -f "$DATABASE_PATH" ]; then
        count=$(sqlite3 "$DATABASE_PATH" "SELECT COUNT(*) FROM ocr_results")
        echo "Database contains $count entries"
    fi
    echo "OCR process completed successfully"
fi

exit 0
