"""Image file rule implementation - 图片文件内容规则实现."""

from __future__ import annotations

from typing import Any

from ...models.fileinfo import FileInfo
from ._base import BaseContentRule

try:
    import pytesseract
    from PIL import Image
except ImportError:
    Image = None
    pytesseract = None


class ImageRule(BaseContentRule):
    """图片文件内容匹配规则 - 对图片文件适用（需要 OCR）."""

    def __init__(self, rule_data: dict[str, Any], *, use_ocr: bool = False) -> None:
        """初始化图片规则.

        Args:
            rule_data: 包含规则配置的字典
            use_ocr: 是否使用 OCR 功能
        """
        super().__init__(rule_data)
        self.file_type = "image"
        self.use_ocr = use_ocr

    def parse_content(self, fileinfo: FileInfo) -> str:
        """从图片文件中提取内容（OCR）.

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        if Image is None or pytesseract is None:
            from ...models.logger import logger

            logger.warning("未安装 PIL 或 pytesseract, 跳过图像 OCR")
            return ""

        if not self.use_ocr:
            return ""

        try:
            img = Image.open(fileinfo.file_path)
            return pytesseract.image_to_string(img)
        except (OSError, ValueError) as e:
            from ...models.logger import logger

            logger.warning(f"无法对 {fileinfo.file_path} 执行 OCR: {e}")
            return ""
