"""Filename rule implementation - 文件名规则实现."""

from __future__ import annotations

import re
from pathlib import Path
from typing import Any

from ..models.fileinfo import FileInfo, MatchInfo
from ..models.logger import logger
from .base import BaseRule, BaseRuleConfig


class FilenameRule(BaseRule):
    """文件名匹配规则 - 对所有类型的文件均适用."""

    def __init__(self, rules: dict[str, Any]) -> None:
        """初始化文件名规则.

        Args:
            rule_data: 包含规则配置的字典
        """
        self.rule_configs = [BaseRuleConfig.from_dict(d) for d in rules.get("filename_rules", [])]

    def match(self, fileinfo: FileInfo) -> MatchInfo | None:
        """匹配文件名.

        Args:
            fileinfo: 文件信息对象

        Returns
        -------
            如果匹配返回 MatchInfo,否则返回 None
        """
        logger.debug("调用文件名匹配规则")
        filename = Path(fileinfo.file_path).name

        # 遍历所有规则配置,收集所有匹配的等级
        all_matches: list[tuple[MatchInfo, int]] = []  # (MatchInfo, level)

        for rule_config in self.rule_configs:
            result = self._match_filename_with_config(filename, fileinfo, rule_config)
            if result:
                all_matches.append((result, rule_config.level))

        # 如果没有匹配到任何规则,返回 None
        if not all_matches:
            return None

        # 检查是否包含多个等级
        unique_levels = {level for _, level in all_matches}
        has_multi_level = 1 if len(unique_levels) > 1 else 0

        # 找到最高等级的匹配
        max_level = max(level for _, level in all_matches)
        best_match = next(match for match, level in all_matches if level == max_level)

        # 设置 filename_multi_level 标记
        # 注意:这里不直接修改 fileinfo,而是在 MatchInfo 的 metadata 中记录
        import json

        metadata = json.loads(best_match.metadata)
        metadata["filename_multi_level"] = has_multi_level
        best_match.metadata = json.dumps(metadata)

        return best_match

    def _match_filename_with_config(
        self,
        filename: str,
        fileinfo: FileInfo,
        rule_config: BaseRuleConfig,
    ) -> MatchInfo | None:
        """使用指定的规则配置检查文件名是否匹配.

        Args:
            filename: 文件名
            fileinfo: 文件信息对象,用于创建 MatchInfo
            rule_config: 规则配置对象

        Returns
        -------
            如果匹配返回 MatchInfo,否则返回 None
        """
        if not filename or not rule_config.patterns:
            logger.debug("文件名或模式为空")
            return None

        matched_pattern = None
        match_position = -1

        # 遍历该规则的所有模式进行匹配
        for _i, pattern_str in enumerate(rule_config.patterns):
            if rule_config.regex:
                # 正则表达式匹配
                compiled_pattern = re.compile(pattern_str)
                match_result = compiled_pattern.search(filename)
                if match_result:
                    matched_pattern = pattern_str
                    match_position = match_result.start()
                    break
            else:
                # 简单文本匹配
                compare_filename = filename if rule_config.case_sensitive else filename.lower()
                search_text = pattern_str if rule_config.case_sensitive else pattern_str.lower()
                pos = compare_filename.find(search_text)
                if pos != -1:
                    matched_pattern = pattern_str
                    match_position = pos
                    break

        # 如果没有匹配到任何模式,返回 None
        if matched_pattern is None:
            return None

        # 创建并返回 MatchInfo 对象
        return MatchInfo(
            file_id=fileinfo.id,
            rule_name=rule_config.name,
            rule_description=rule_config.description,
            match_type="regex" if rule_config.regex else "text",
            analysis_type="filename",
            line_number=0,  # 文件名匹配不涉及行号
            match_text=matched_pattern,
            start_pos=match_position,
            end_pos=match_position + len(matched_pattern) if match_position >= 0 else -1,
            context_lines=[f"文件名:{filename}"],
            is_skipped=0,
            skip_reason="",
            metadata="{}",
        )
