"""Analyser module for rules."""

from __future__ import annotations

import time

from ..models.config import conf
from ..models.fileinfo import AnalyseResult, FileInfo, MatchInfo
from ..models.logger import logger
from .content._base import BaseContentRule
from .content.csv import CsvRule
from .content.docx import DocxRule
from .content.epub import EpubRule
from .content.html import HtmlRule
from .content.image import ImageRule
from .content.markdown import MarkdownRule
from .content.odt import OdtRule
from .content.pdf import PdfRule
from .content.pptx import PptxRule
from .content.rtf import RtfRule
from .content.xlsx import XlsxRule
from .content.xml import XmlRule
from .content.zipfile import ZipfileRule
from .filename import FilenameRule


class Analyser:
    """通用文件分析器."""

    def __init__(self) -> None:
        self.filename_rule = FilenameRule(conf.RULES)
        self.content_rules: dict[str, BaseContentRule | ZipfileRule] = {
            "pdf": PdfRule(conf.RULES, use_ocr=conf.USE_PDF_OCR),
            "doc": DocxRule(conf.RULES),
            "docx": DocxRule(conf.RULES),
            "xlsx": XlsxRule(conf.RULES),
            "xls": XlsxRule(conf.RULES),
            "pptx": PptxRule(conf.RULES),
            "ppt": PptxRule(conf.RULES),
            "odt": OdtRule(conf.RULES),
            "rtf": RtfRule(conf.RULES),
            "epub": EpubRule(conf.RULES),
            "csv": CsvRule(conf.RULES),
            "xml": XmlRule(conf.RULES),
            "html": HtmlRule(conf.RULES),
            "htm": HtmlRule(conf.RULES),
            "md": MarkdownRule(conf.RULES),
            "jpg": ImageRule(conf.RULES),
            "jpeg": ImageRule(conf.RULES),
            "png": ImageRule(conf.RULES),
            "gif": ImageRule(conf.RULES),
            "bmp": ImageRule(conf.RULES),
            "tiff": ImageRule(conf.RULES),
            "zip": ZipfileRule(conf.RULES),
        }

    def analyse(self, fileinfo: FileInfo) -> AnalyseResult:
        """分析文件并返回完整结果.

        Args:
            fileinfo: 文件信息

        Returns
        -------
            AnalyseResult 对象,包含文件信息,匹配结果,处理时间和状态
        """
        start_time = time.perf_counter()

        try:
            # 更新文件状态为分析中
            fileinfo.analyse_status = "analysing"

            matches: list[MatchInfo] = []

            # 文件名规则匹配
            filename_match = self.filename_rule.match(fileinfo)
            if filename_match:
                matches.append(filename_match)

            # 内容规则匹配 - 收集所有匹配项
            analyser = self.content_rules.get(fileinfo.extension, None)
            if analyser is not None:
                # 使用 find_all_matches 获取所有内容匹配
                content_matches = analyser.find_all_matches(fileinfo)
                matches.extend(content_matches)
            else:
                logger.debug(f"无法分析文件 {fileinfo.full_path},扩展名 {fileinfo.extension}")

            # 计算处理时间
            processing_time = time.perf_counter() - start_time

            # 更新文件信息
            fileinfo.processing_time_seconds = processing_time
            fileinfo.match_count = len(matches)
            fileinfo.analyse_status = "completed"

            return AnalyseResult(
                fileinfo=fileinfo,
                matches=matches,
                processing_time_seconds=processing_time,
                status="completed",
            )

        except (OSError, ValueError, RuntimeError, TypeError, AttributeError, ImportError) as e:
            # 捕获所有可能的运行时异常以确保文件分析不会崩溃
            # 这些异常可能来自:文件读取失败,格式解析错误,第三方库依赖问题等
            processing_time = time.perf_counter() - start_time
            logger.error(f"分析文件失败 {fileinfo.full_path}: {e}", exc_info=True)

            fileinfo.processing_time_seconds = processing_time
            fileinfo.analyse_status = "error"

            return AnalyseResult(
                fileinfo=fileinfo,
                matches=[],
                processing_time_seconds=processing_time,
                status="error",
                error_message=str(e),
            )
