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

from __future__ import annotations

from pathlib import Path
from typing import Any

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

# RTF 提取常量
RTF_PRINTABLE_MIN = 32  # Space character
RTF_PRINTABLE_MAX = 126  # Tilde character (~)


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

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

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

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

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        try:
            content = Path(fileinfo.file_path).read_bytes()

            text = ""
            i = 0
            while i < len(content):
                if content[i] == ord("\\") and i + 1 < len(content):
                    if content[i + 1] in {ord("'"), ord("*"), ord("\\")}:
                        i += 2
                        continue
                    while (
                        i < len(content)
                        and content[i] != ord(" ")
                        and content[i] != ord("{")
                        and content[i] != ord("}")
                    ):
                        i += 1
                elif RTF_PRINTABLE_MIN <= content[i] <= RTF_PRINTABLE_MAX:
                    text += chr(content[i])
                i += 1
        except (OSError, ValueError) as e:
            from ...models.logger import logger

            logger.warning(f"提取 RTF 时出错:{e}")
            return ""
        else:
            return text
