"""敏感词过滤服务"""

import re
from dataclasses import dataclass, field
from typing import Optional

# 基础敏感词库
SENSITIVE_WORDS = {
    "politics": [
        "台湾", "西藏", "新疆", "香港", "澳门",
        "分裂", "独立", "抗议", "游行", "示威",
        "政治", "敏感词",
    ],
    "medical": [
        "药品", "治疗", "疗效", "治愈",
        "处方", "医生", "医院", "手术",
        "医疗", "敏感词",
    ],
    "finance": [
        "投资", "理财", "收益率", "回报",
        "股票", "基金", "债券", "期货",
    ],
    "adult": [
        "色情", "赌博", "毒品", "暴力",
    ],
}

REPLACEMENT_CHAR = "*"


@dataclass
class FoundWord:
    """发现的敏感词"""
    word: str
    category: str
    position: int
    replacement: str


@dataclass
class FilterResult:
    """过滤结果"""
    filtered_content: str
    found_words: list = field(default_factory=list)
    replacements: dict = field(default_factory=dict)


class SensitiveFilter:
    """敏感词过滤器"""

    def __init__(self):
        self.custom_words: dict = {}
        self.replacement_char = REPLACEMENT_CHAR

    def filter(self, content: str, platform: str) -> FilterResult:
        """过滤敏感词

        Args:
            content: 待过滤的内容
            platform: 平台标识

        Returns:
            FilterResult: 包含过滤后内容、发现的敏感词和替换映射
        """
        # 获取平台的敏感词配置
        from app.services.distribution.platform_rules import PLATFORM_RULES

        rules = PLATFORM_RULES.get(platform, {})
        sensitive_config = rules.get("sensitive_words", {})

        check_required = sensitive_config.get("check_required", True)
        if not check_required:
            return FilterResult(content, [], {})

        categories = sensitive_config.get("categories", ["politics"])
        max_tolerance = sensitive_config.get("max_tolerance", 0)

        # 合并基础词库和自定义词库
        all_words = {}
        for cat in categories:
            all_words[cat] = []
            if cat in SENSITIVE_WORDS:
                all_words[cat].extend(SENSITIVE_WORDS[cat])
            if cat in self.custom_words:
                all_words[cat].extend(self.custom_words[cat])

        # 自定义分类的词也需要检查，将其合并到所有启用的分类中
        for custom_cat, custom_words_list in self.custom_words.items():
            if custom_cat not in categories:
                # 自定义分类不在平台启用分类中，将其添加到第一个分类
                target_cat = categories[0]
                all_words[target_cat].extend(custom_words_list)

        found_words = []
        filtered = content
        replacements = {}

        for category, words in all_words.items():
            for word in words:
                if word in filtered:
                    # 记录发现的敏感词
                    position = filtered.find(word)
                    found_words.append(FoundWord(
                        word=word,
                        category=category,
                        position=position,
                        replacement=self.replacement_char * len(word)
                    ))
                    # 替换敏感词
                    replacement = self.replacement_char * len(word)
                    filtered = filtered.replace(word, replacement)
                    replacements[word] = replacement

        return FilterResult(
            filtered_content=filtered,
            found_words=found_words,
            replacements=replacements
        )

    def add_custom_words(self, category: str, words: list):
        """添加自定义敏感词

        Args:
            category: 敏感词分类
            words: 敏感词列表
        """
        if category not in self.custom_words:
            self.custom_words[category] = []
        self.custom_words[category].extend(words)
