#!/usr/bin/env bash
# ocr-screenshot.sh — slurp + grim → zbar/tesseract → wl-clipboard

set -euo pipefail

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

IMG="$TMPDIR/shot.png"
PROC="$TMPDIR/proc.png"
TXT="$TMPDIR/out"

GEOMETRY=$(slurp) || {
  notify-send "OCR" "Отменено"
  exit 0
}
grim -g "$GEOMETRY" "$IMG"

# 1. Сначала пробуем zbar (QR, штрихкоды)
QR_RESULT=$(zbarimg --quiet --raw "$IMG" 2>/dev/null || true)

if [[ -n "$QR_RESULT" ]]; then
  printf '%s' "$QR_RESULT" | wl-copy
  xdg-open "${QR_RESULT:0:80}"
  exit 0
fi

# 2. Если QR не найден — обычный OCR
#magick "$IMG" \
#  -colorspace Gray \
#  -resize 300% \
#  -unsharp 0x1 \
#  -threshold 50% \
#  "$PROC"

magick "$IMG" \
  -colorspace Gray \
  -resize 300% \
  -unsharp 0x0.5+1+0 \
  -level 20%,80% \
  "$PROC"
tesseract "$PROC" "$TXT" \
  -l rus+eng \
  --oem 1 \
  --psm 4 \
  -c preserve_interword_spaces=1 \
  2>/dev/null

RESULT=$(cat "${TXT}.txt" | sed '/^$/d' | sed 's/[[:space:]]\+/ /g' | xargs)

if [[ -z "$RESULT" ]]; then
  notify-send "OCR" "Ничего не распознано"
  exit 1
fi

printf '%s' "$RESULT" | wl-copy
notify-send "OCR — Текст" "Скопировано: ${RESULT:0:80}…"
