"""OCR — extract text from screen regions using pytesseract (optional)."""

import io
import base64


def ocr_screen():
    """OCR the entire screen."""
    try:
        from .screenshot import take_screenshot
        result = take_screenshot()
        if not result.get("success"):
            return result
        return _ocr_from_base64(result["image"])
    except Exception as e:
        return {"success": False, "error": str(e)}


def ocr_region(x, y, width, height):
    """OCR a specific screen region."""
    try:
        from .screenshot import take_region_screenshot
        result = take_region_screenshot(x, y, width, height)
        if not result.get("success"):
            return result
        return _ocr_from_base64(result["image"])
    except Exception as e:
        return {"success": False, "error": str(e)}


def _ocr_from_base64(img_b64):
    """Run OCR on a base64 PNG image."""
    try:
        import pytesseract
        from PIL import Image

        img_bytes = base64.b64decode(img_b64)
        img = Image.open(io.BytesIO(img_bytes))
        text = pytesseract.image_to_string(img)
        return {"success": True, "text": text.strip()}
    except ImportError:
        return {
            "success": False,
            "error": "pytesseract not installed. Install with: pip install pytesseract (and install Tesseract OCR on your system)",
        }
    except Exception as e:
        return {"success": False, "error": str(e)}
