"""Optional OCR text extraction from images.

Uses pytesseract (Apache 2.0) + Pillow (HPND/MIT-compatible).
Gracefully returns empty string if Tesseract is not installed.
"""

from __future__ import annotations

import logging
from pathlib import Path

log = logging.getLogger(__name__)

_TESSERACT_AVAILABLE: bool | None = None


def _check_tesseract() -> bool:
    """Check once whether Tesseract is installed and reachable."""
    global _TESSERACT_AVAILABLE
    if _TESSERACT_AVAILABLE is not None:
        return _TESSERACT_AVAILABLE

    try:
        import pytesseract
        pytesseract.get_tesseract_version()
        _TESSERACT_AVAILABLE = True
        log.info("Tesseract OCR available: %s", pytesseract.get_tesseract_version())
    except Exception:
        _TESSERACT_AVAILABLE = False
        log.debug("Tesseract OCR not available — OCR will be skipped")
    return _TESSERACT_AVAILABLE


def extract_text(image_path: Path) -> str:
    """Extract text from an image file using Tesseract OCR.

    Returns extracted text, or empty string if OCR is unavailable or fails.
    """
    if not _check_tesseract():
        return ""

    try:
        import pytesseract
        from PIL import Image

        img = Image.open(image_path)

        # Convert to RGB if needed (RGBA, palette, etc.)
        if img.mode not in ("RGB", "L"):
            img = img.convert("RGB")

        text = pytesseract.image_to_string(img).strip()

        if text:
            log.info("OCR extracted %d chars from %s", len(text), image_path.name)
        return text
    except Exception as e:
        log.warning("OCR failed for %s: %s", image_path.name, e)
        return ""
