#!/usr/bin/env bash
# render_pdf.sh — рендер PDF в PNG для визуальной вычитки.
# Usage: render_pdf.sh <pdf> [dpi=110] [pages=all|N|A-B] [outdir=/tmp/pdfqa]
# Печатает число страниц и абсолютные пути PNG, которые надо открыть через Read.
set -euo pipefail

PDF="${1:?usage: render_pdf.sh <pdf> [dpi] [pages] [outdir]}"
DPI="${2:-110}"
PAGES="${3:-all}"
OUT="${4:-/tmp/pdfqa}"

[ -f "$PDF" ] || { echo "ERROR: no such file: $PDF" >&2; exit 1; }
command -v pdftoppm >/dev/null || { echo "ERROR: pdftoppm not found (brew install poppler)" >&2; exit 1; }

mkdir -p "$OUT"
BASE="$OUT/$(basename "${PDF%.*}" | tr ' ' '_')"
rm -f "${BASE}"-*.png 2>/dev/null || true

RANGE=()
if [ "$PAGES" != "all" ]; then
  if [[ "$PAGES" == *-* ]]; then
    RANGE=(-f "${PAGES%-*}" -l "${PAGES#*-}")
  else
    RANGE=(-f "$PAGES" -l "$PAGES")
  fi
fi

pdftoppm -png -r "$DPI" ${RANGE[@]+"${RANGE[@]}"} "$PDF" "$BASE"

NPAGES="$(pdfinfo "$PDF" 2>/dev/null | awk '/^Pages:/{print $2}')"
echo "PDF pages total: ${NPAGES:-?}   (rendered @ ${DPI} dpi, pages=${PAGES})"
echo "Open these with Read:"
ls -1 "${BASE}"-*.png
