"""ODT file rule implementation - ODT 文件内容规则实现."""

from __future__ import annotations

from typing import Any

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

try:
    import odf.opendocument as odf_odt
except ImportError:
    odf_odt = None


class OdtRule(BaseContentRule):
    """ODT 文件内容匹配规则 - 对 ODT 文件适用."""

    def __init__(self, rule_data: dict[str, Any]) -> None:
        """初始化 ODT 规则.

        Args:
            rule_data: 包含规则配置的字典
        """
        super().__init__(rule_data)
        self.file_type = "odt"

    def parse_content(self, fileinfo: FileInfo) -> str:
        """从 ODT 文件中提取内容.

        Args:
            fileinfo: 文件信息对象

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

            logger.warning("未安装 odfpy, 跳过 ODT 提取")
            return ""

        try:
            doc = odf_odt.load(fileinfo.file_path)
        except (OSError, ValueError) as e:
            from ...models.logger import logger

            logger.warning(f"提取 ODT 时出错: {e}")
            return ""
        else:
            return doc.textual_content
