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

from __future__ import annotations

import html
import re
from typing import Any

try:
    import ebooklib
    from ebooklib import epub
except ImportError:
    ebooklib = None

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


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

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

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

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

        Args:
            fileinfo: 文件信息对象

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

            logger.warning("未安装 ebooklib, 跳过 EPUB 提取")
            return ""

        try:
            book = epub.read_epub(fileinfo.file_path)
            text_parts = []

            for item in book.get_items():
                if item.get_type() == ebooklib.ITEM_DOCUMENT:
                    html_content = item.get_content().decode("utf-8")
                    # 移除 HTML 标签
                    text = re.sub(r"<[^>]+>", " ", html_content)
                    # 解码 HTML 实体
                    text = html.unescape(text)
                    text_parts.append(text)

            return "\n\n".join(text_parts) if text_parts else ""
        except (OSError, ValueError) as e:
            from ...models.logger import logger

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