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

from __future__ import annotations

import csv
from pathlib import Path
from typing import Any

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


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

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

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

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

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            提取的文本内容
        """
        try:
            text_parts = []
            with Path(fileinfo.file_path).open(encoding="utf-8", errors="ignore") as f:
                reader = csv.reader(f)
                for row in reader:
                    row_text = " | ".join(str(cell) for cell in row)
                    text_parts.append(row_text)

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

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