"""
禁忌过滤系统 2.0 - 增强版
包含地域习俗、宗教禁忌、年龄禁忌，以及禁忌解释和替代方案
"""
from typing import List, Dict, Optional, Tuple
import random

class GiftFilterV2:
    """礼物禁忌过滤器 2.0"""

    # 扩展禁忌库
    TABOOS = {
        # 谐音禁忌（核心）
        "钟": {
            "reason": "谐音'送终'，寓意不吉利",
            "alternatives": ["电子闹钟", "沙漏", "创意时钟装饰品"],
            "category": "谐音禁忌",
            "severity": "high"
        },
        "鞋": {
            "reason": "谐音'送邪'，可能带来霉运",
            "alternatives": ["袜子礼盒", "足浴盆", "休闲拖鞋礼盒"],
            "category": "谐音禁忌",
            "severity": "high"
        },
        "梨": {
            "reason": "谐音'分离'，不适合情侣、夫妻",
            "alternatives": ["苹果（平安）", "橙子（心想事成）", "火龙果（红红火火）"],
            "category": "谐音禁忌",
            "severity": "medium"
        },
        "伞": {
            "reason": "谐音'散'，寓意分离、解散",
            "alternatives": ["雨衣", "遮阳帽", "便携式晴雨伞（需避免直接说'伞'）"],
            "category": "谐音禁忌",
            "severity": "medium"
        },
        
        # 丧事相关
        "蜡烛": {
            "reason": "传统祭祀用品，不宜作为日常礼物",
            "alternatives": ["香薰灯", "小夜灯", "创意灯具"],
            "category": "丧事禁忌",
            "severity": "high"
        },
        "白花": {
            "reason": "探病、祭祀专用，日常不宜",
            "alternatives": ["粉色系花束", "金色系花束", "干花花束"],
            "category": "丧事禁忌",
            "severity": "high"
        },
        "菊花": {
            "reason": "传统祭祀用花，部分地区忌讳",
            "alternatives": ["向日葵", "郁金香", "百合花"],
            "category": "丧事禁忌",
            "severity": "medium"
        },
        
        # 数字禁忌
        "4": {
            "reason": "谐音'死'，不吉利数字",
            "alternatives": ["避免4的数量，建议用3、6、8、9"],
            "category": "数字禁忌",
            "severity": "medium"
        },
        
        # 物品寓意禁忌
        "手帕": {
            "reason": "传统中寓意'擦眼泪'，可能带来离别",
            "alternatives": ["毛巾礼盒", "围巾", "丝巾"],
            "category": "寓意禁忌",
            "severity": "low"
        },
        "刀剪": {
            "reason": "尖锐物品，寓意'一刀两断'",
            "alternatives": ["多功能工具箱", "厨房实用套装", "精美餐具礼盒"],
            "category": "寓意禁忌",
            "severity": "medium"
        },
        "钱包": {
            "reason": "寓意'送出财富'，部分地区忌讳",
            "alternatives": ["不空钱包", "里面放少量钱，寓意'有钱'"],
            "category": "寓意禁忌",
            "severity": "low"
        },
    }

    # 地域习俗禁忌
    REGIONAL_TABOOS = {
        # 广东地区
        "广东": {
            "禁忌": ["梨", "伞", "钟", "四", "白事物品"],
            "备注": "注重谐音和数字吉利"
        },
        # 福建地区
        "福建": {
            "禁忌": ["红绳", "单数礼物"],
            "备注": "红色为吉祥色，送礼成双"
        },
        # 西北地区
        "西北": {
            "禁忌": ["猪肉制品"],
            "备注": "尊重民族习俗"
        }
    }

    # 宗教禁忌
    RELIGIOUS_TABOOS = {
        "佛教": {
            "禁忌": ["皮革制品", "酒精", "荤腥"],
            "备注": "尊重戒律，宜送素食、香、佛教相关"
        },
        "基督教": {
            "禁忌": ["偶像崇拜物品", "不吉利数字13"],
            "备注": "避免与异教相关的礼物"
        },
        "伊斯兰教": {
            "禁忌": ["猪肉制品", "酒精", "偶像"],
            "备注": "严格遵守教义"
        }
    }

    # 年龄禁忌
    AGE_TABOOS = {
        "长辈": {
            "禁忌": ["钟表", "白事物品", "4相关"],
            "备注": "避讳不吉利谐音"
        },
        "情侣": {
            "禁忌": ["梨", "伞", "手帕"],
            "备注": "避免分离寓意"
        },
        "病人": {
            "禁忌": ["钟", "蜡烛", "白花"],
            "备注": "避讳不吉利物品"
        }
    }

    def filter(
        self, 
        gifts: List[Dict], 
        relation: str = None,
        region: str = None,
        religion: str = None,
        age_group: str = None
    ) -> Tuple[List[Dict], Dict]:
        """
        过滤禁忌礼物，返回过滤后的列表和禁忌报告

        Args:
            gifts: 礼物列表
            relation: 收礼人关系
            region: 地区（如"广东"）
            religion: 宗教
            age_group: 年龄组（如"长辈"）

        Returns:
            Tuple[过滤后的礼物列表, 禁忌报告]
        """
        filtered = []
        taboo_report = {
            "total_checked": len(gifts),
            "taboo_gifts": [],
            "warnings": [],
            "suggestions": []
        }

        for gift in gifts:
            name = gift.get("name", "")
            found_taboo = None
            
            # 1. 检查通用禁忌
            for taboo_word, info in self.TABOOS.items():
                if taboo_word in name:
                    found_taboo = {
                        "gift_name": name,
                        "taboo_word": taboo_word,
                        "reason": info["reason"],
                        "alternatives": info["alternatives"],
                        "category": info["category"],
                        "severity": info["severity"],
                        "type": "通用禁忌"
                    }
                    break
            
            # 2. 检查关系特殊禁忌
            if relation and not found_taboo:
                found_taboo = self._check_relation_taboo(name, relation)
            
            # 3. 检查地域禁忌
            if region and not found_taboo:
                found_taboo = self._check_regional_taboo(name, region)
            
            # 4. 检查宗教禁忌
            if religion and not found_taboo:
                found_taboo = self._check_religious_taboo(name, religion)
            
            # 5. 检查年龄禁忌
            if age_group and not found_taboo:
                found_taboo = self._check_age_taboo(name, age_group)
            
            if found_taboo:
                taboo_report["taboo_gifts"].append(found_taboo)
                
                # 根据严重程度添加警告和建议
                if found_taboo["severity"] in ["high", "medium"]:
                    taboo_report["warnings"].append(
                        f"⚠️ '{name}'包含禁忌：{found_taboo['reason']}"
                    )
                    if found_taboo["alternatives"]:
                        suggestion = random.choice(found_taboo["alternatives"])
                        taboo_report["suggestions"].append(
                            f"💡 建议替代品：{suggestion}"
                        )
            else:
                filtered.append(gift)
        
        # 生成汇总报告
        self._generate_summary_report(taboo_report)
        
        return filtered, taboo_report

    def _check_relation_taboo(self, gift_name: str, relation: str) -> Optional[Dict]:
        """检查关系禁忌"""
        # 情侣关系禁忌
        if "女友" in relation or "男友" in relation or "情侣" in relation:
            taboo_words = ["梨", "伞", "手帕", "4", "钟"]
            for taboo in taboo_words:
                if taboo in gift_name:
                    return {
                        "gift_name": gift_name,
                        "taboo_word": taboo,
                        "reason": f"情侣间禁忌：{self.TABOOS.get(taboo, {}).get('reason', '不吉利')}",
                        "alternatives": self.TABOOS.get(taboo, {}).get("alternatives", []),
                        "category": "关系禁忌",
                        "severity": "medium",
                        "type": "情侣禁忌"
                    }
        
        # 长辈关系禁忌
        if "长辈" in relation or "父母" in relation or "爷爷奶奶" in relation:
            taboo_words = ["钟", "蜡烛", "4", "白花"]
            for taboo in taboo_words:
                if taboo in gift_name:
                    return {
                        "gift_name": gift_name,
                        "taboo_word": taboo,
                        "reason": f"长辈禁忌：{self.TABOOS.get(taboo, {}).get('reason', '不吉利')}",
                        "alternatives": self.TABOOS.get(taboo, {}).get("alternatives", []),
                        "category": "关系禁忌",
                        "severity": "high",
                        "type": "长辈禁忌"
                    }
        
        # 病人禁忌
        if "病人" in relation:
            taboo_words = ["钟", "蜡烛", "白花", "4"]
            for taboo in taboo_words:
                if taboo in gift_name:
                    return {
                        "gift_name": gift_name,
                        "taboo_word": taboo,
                        "reason": f"探望病人禁忌：{self.TABOOS.get(taboo, {}).get('reason', '不吉利')}",
                        "alternatives": self.TABOOS.get(taboo, {}).get("alternatives", []),
                        "category": "关系禁忌",
                        "severity": "high",
                        "type": "病人禁忌"
                    }
        
        return None

    def _check_regional_taboo(self, gift_name: str, region: str) -> Optional[Dict]:
        """检查地域禁忌"""
        region_info = self.REGIONAL_TABOOS.get(region)
        if not region_info:
            return None
        
        for taboo in region_info["禁忌"]:
            if taboo in gift_name:
                reason = self.TABOOS.get(taboo, {}).get("reason", "地区习俗禁忌")
                return {
                    "gift_name": gift_name,
                    "taboo_word": taboo,
                    "reason": f"{region}地区习俗：{reason}",
                    "alternatives": self.TABOOS.get(taboo, {}).get("alternatives", []),
                    "category": "地域禁忌",
                    "severity": "medium",
                    "type": f"{region}地区禁忌"
                }
        
        return None

    def _check_religious_taboo(self, gift_name: str, religion: str) -> Optional[Dict]:
        """检查宗教禁忌"""
        religion_info = self.RELIGIOUS_TABOOS.get(religion)
        if not religion_info:
            return None
        
        for taboo in religion_info["禁忌"]:
            if taboo in gift_name:
                return {
                    "gift_name": gift_name,
                    "taboo_word": taboo,
                    "reason": f"{religion}禁忌：{religion_info['备注']}",
                    "alternatives": [],
                    "category": "宗教禁忌",
                    "severity": "high",
                    "type": f"{religion}禁忌"
                }
        
        return None

    def _check_age_taboo(self, gift_name: str, age_group: str) -> Optional[Dict]:
        """检查年龄禁忌"""
        age_info = self.AGE_TABOOS.get(age_group)
        if not age_info:
            return None
        
        for taboo in age_info["禁忌"]:
            if taboo in gift_name:
                reason = self.TABOOS.get(taboo, {}).get("reason", "年龄组禁忌")
                return {
                    "gift_name": gift_name,
                    "taboo_word": taboo,
                    "reason": f"{age_group}禁忌：{reason}",
                    "alternatives": self.TABOOS.get(taboo, {}).get("alternatives", []),
                    "category": "年龄禁忌",
                    "severity": "medium",
                    "type": f"{age_group}禁忌"
                }
        
        return None

    def _generate_summary_report(self, report: Dict):
        """生成汇总报告"""
        total_taboo = len(report["taboo_gifts"])
        if total_taboo == 0:
            report["summary"] = "✅ 未发现禁忌礼物"
            return
        
        # 统计严重程度
        high_severity = sum(1 for g in report["taboo_gifts"] if g["severity"] == "high")
        medium_severity = sum(1 for g in report["taboo_gifts"] if g["severity"] == "medium")
        low_severity = sum(1 for g in report["taboo_gifts"] if g["severity"] == "low")
        
        # 生成总结
        summary_parts = [f"⚠️ 发现{total_taboo}个禁忌礼物"]
        
        if high_severity > 0:
            summary_parts.append(f"高危禁忌：{high_severity}个")
        if medium_severity > 0:
            summary_parts.append(f"中危禁忌：{medium_severity}个")
        if low_severity > 0:
            summary_parts.append(f"低危禁忌：{low_severity}个")
        
        report["summary"] = " | ".join(summary_parts)

    def explain_taboo(self, gift_name: str, relation: str = None) -> str:
        """
        解释为什么某个礼物可能不适宜
        
        Args:
            gift_name: 礼物名称
            relation: 收礼人关系
            
        Returns:
            解释文本
        """
        explanations = []
        
        # 检查通用禁忌
        for taboo_word, info in self.TABOOS.items():
            if taboo_word in gift_name:
                explanation = f"'{gift_name}'中包含'{taboo_word}'："
                explanation += f"{info['reason']}"
                
                if info['alternatives']:
                    explanation += f" 推荐替代品：{', '.join(info['alternatives'][:3])}"
                
                explanations.append(explanation)
        
        # 检查关系禁忌
        if relation:
            relation_explanation = self._check_relation_taboo(gift_name, relation)
            if relation_explanation:
                explanations.append(f"对于{relation}：{relation_explanation['reason']}")
        
        if explanations:
            return "\n".join(explanations)
        else:
            return f"✅ '{gift_name}'暂无发现禁忌"

    def get_safe_alternatives(self, taboo_gift: str) -> List[str]:
        """
        获取禁忌礼物的安全替代品
        
        Args:
            taboo_gift: 禁忌礼物名称
            
        Returns:
            替代品列表
        """
        alternatives = []
        
        for taboo_word, info in self.TABOOS.items():
            if taboo_word in taboo_gift:
                alternatives.extend(info["alternatives"])
        
        # 去重并返回
        return list(set(alternatives)) if alternatives else []


# 使用示例
if __name__ == "__main__":
    filter_v2 = GiftFilterV2()
    
    # 示例礼物
    test_gifts = [
        {"name": "精美时钟", "price": 299, "reason": "美观实用"},
        {"name": "水晶梨果篮", "price": 199, "reason": "新鲜美味"},
        {"name": "蓝牙耳机", "price": 399, "reason": "科技感十足"},
        {"name": "白菊花束", "price": 99, "reason": "清新淡雅"},
    ]
    
    # 过滤礼物（考虑地区广东，关系情侣）
    filtered_gifts, report = filter_v2.filter(
        gifts=test_gifts,
        relation="情侣",
        region="广东"
    )
    
    print("=== 禁忌报告 ===")
    print(f"总结：{report['summary']}")
    print(f"过滤后礼物数：{len(filtered_gifts)}")
    
    if report["warnings"]:
        print("\n⚠️ 警告：")
        for warning in report["warnings"]:
            print(f"  {warning}")
    
    if report["suggestions"]:
        print("\n💡 建议：")
        for suggestion in report["suggestions"]:
            print(f"  {suggestion}")
    
    print("\n=== 详细解释 ===")
    for gift in test_gifts:
        print(f"\n{gift['name']}：")
        print(filter_v2.explain_taboo(gift["name"], "情侣"))