"""
推荐理由生成 - 智能生成有说服力的推荐理由
优化版本：基于评分的个性化理由生成
"""
from typing import Dict, List, Optional

class ReasonGenerator:
    """推荐理由生成器 - 智能版"""

    # 风格模板（扩展）
    STYLE_TEMPLATES = {
        "实用型": {
            "高性价比": "实用贴心，性价比出色，是用心之选",
            "心意满分": "实用性强，真正解决日常需求，体现你的用心",
            "品质之选": "实用又不失品质，日常必备好物",
        },
        "浪漫型": {
            "惊喜满分": "浪漫温馨，充满惊喜，定能打动TA的心",
            "仪式感强": "充满仪式感，让这个特殊时刻更加难忘",
            "爱意满满": "浪漫告白，完美传达你的深情厚意",
        },
        "健康型": {
            "关怀入微": "关心健康，是最贴心的呵护",
            "养生之选": "健康是最珍贵的礼物，体现你的关怀",
            "体贴暖心": "健康养生，表达你无微不至的关怀",
        },
        "科技型": {
            "时尚潮流": "科技感十足，紧跟时代潮流",
            "品质提升": "智能便捷，显著提升生活品质",
            "酷炫实用": "科技与实用完美结合，现代感满满",
        },
        "惊喜型": {
            "意外之喜": "独特的惊喜，打破常规，让TA眼前一亮",
            "创意满分": "创意十足，这份礼物一定让TA印象深刻",
            "与众不同": "独特别致，在众多选择中脱颖而出",
        },
        "意义型": {
            "珍贵纪念": "蕴含深意，值得珍藏的美好回忆",
            "情感满满": "饱含心意，是最好的情感表达",
            "用心之选": "意义非凡，体现你的深思熟虑",
        },
        "酷炫型": {
            "潮流时尚": "酷炫有型，彰显个性与品味",
            "紧跟潮流": "时尚前沿，是年轻人的心头好",
            "个性十足": "独特酷炫，展现不凡品味",
        },
        "有趣型": {
            "趣味横生": "有趣好玩，带来无尽欢乐",
            "轻松愉快": "幽默风趣，传递快乐能量",
            "创意无限": "创意有趣，让人会心一笑",
        },
        "奢华型": {
            "尊贵品质": "奢华典雅，彰显尊贵品味",
            "精致高端": "高端精致，品质生活的象征",
            "奢华之选": "奢华大气，是最好的心意表达",
        },
        "教育型": {
            "启迪智慧": "益智有趣，开发智力启迪思维",
            "成长助力": "寓教于乐，助力成长与学习",
            "知识宝库": "知识丰富，是最好的智力投资",
        },
        "正式型": {
            "体面大方": "正式体面，适合重要场合",
            "品质之选": "品质上乘，体现专业与尊重",
            "经典稳重": "稳重大方，恰到好处的选择",
        },
        "敬意型": {
            "尊重感恩": "表达敬意，体现感恩之心",
            "尊崇有礼": "恭敬有礼，最合适的敬意表达",
            "心怀敬意": "充满敬意，表达你的尊重与感激",
        },
        "default": {
            "默认": "这是一份用心挑选的礼物",
        },
    }

    # 关系模板（扩展）
    RELATION_TEMPLATES = {
        # 情侣关系
        "女友": {
            "高心意": "女友一定会被你的深情打动",
            "高惊喜": "这份惊喜会让女友感到甜蜜幸福",
            "高性价比": "女友会感受到你的用心和体贴",
        },
        "男友": {
            "高心意": "男友会感受到你的爱意和用心",
            "高惊喜": "这份惊喜会让男友眼前一亮",
            "高性价比": "男友会欣赏你的贴心选择",
        },
        "老婆": {
            "高心意": "老婆会为你的用心感到幸福满满",
            "高惊喜": "这份惊喜会让老婆感动不已",
            "高性价比": "老婆会感受到你的体贴与关爱",
        },
        "老公": {
            "高心意": "老公会为你的用心感到温暖",
            "高惊喜": "这份惊喜会让老公感受到你的爱意",
            "高性价比": "老公会欣赏你的贤惠与贴心",
        },
        "伴侣": {
            "高心意": "伴侣会感受到你满满的爱意",
            "高惊喜": "这份惊喜会让感情更加甜蜜",
            "高性价比": "伴侣会为你的用心选择感到温暖",
        },
        "喜欢的人": {
            "高心意": "TA会感受到你的真挚心意",
            "高惊喜": "这份惊喜会让TA对你印象深刻",
            "高性价比": "TA会感受到你的用心与诚意",
        },
        
        # 父母关系
        "妈妈": {
            "高心意": "妈妈一定会感受到你的孝心",
            "高惊喜": "这份惊喜会让妈妈感到欣慰",
            "高性价比": "妈妈会为你的贴心实用感到欣慰",
        },
        "爸爸": {
            "高心意": "爸爸会为你的用心感到骄傲",
            "高惊喜": "这份惊喜会让爸爸感到意外和开心",
            "高性价比": "爸爸会欣赏你的务实和贴心",
        },
        "奶奶": {
            "高心意": "奶奶会感受到你的孝顺和关怀",
            "高性价比": "奶奶会为你的贴心感到欣慰",
        },
        "爷爷": {
            "高心意": "爷爷会感受到你的孝心和敬重",
            "高性价比": "爷爷会为你的贴心感到欣慰",
        },
        "长辈": {
            "高心意": "长辈会感受到你的敬重与关怀",
            "高性价比": "长辈会为你的贴心感到欣慰",
        },
        
        # 朋友关系
        "闺蜜": {
            "高心意": "闺蜜会为你的贴心感到温暖",
            "高惊喜": "这份惊喜会让闺蜜开心不已",
            "高性价比": "闺蜜会欣赏你的用心选择",
        },
        "兄弟": {
            "高心意": "兄弟会为你的义气感到温暖",
            "高惊喜": "这份惊喜会让兄弟眼前一亮",
            "高性价比": "兄弟会欣赏你的贴心和实用",
        },
        "朋友": {
            "高心意": "朋友会为你的贴心感到温暖",
            "高惊喜": "这份惊喜会让朋友感到意外和开心",
            "高性价比": "朋友会欣赏你的用心选择",
        },
        "姐妹": {
            "高心意": "姐妹会感受到你的关爱",
            "高惊喜": "这份惊喜会让姐妹感到开心",
            "高性价比": "姐妹会欣赏你的贴心选择",
        },
        
        # 孩子关系
        "孩子": {
            "高心意": "孩子会感受到你的关爱",
            "高惊喜": "这份惊喜会让孩子开心不已",
            "高性价比": "孩子会喜欢这个实用又有趣的礼物",
        },
        "儿童": {
            "高心意": "小朋友会感受到你的关爱",
            "高惊喜": "这份惊喜会让小朋友开心不已",
            "高性价比": "小朋友会喜欢这个贴心的礼物",
        },
        "学生": {
            "高心意": "学生会感受到你的鼓励和关怀",
            "高惊喜": "这份惊喜会让学生感到开心",
            "高性价比": "学生会喜欢这个实用的礼物",
        },
        
        # 职场关系
        "领导": {
            "高心意": "领导会感受到你的尊重和用心",
            "高性价比": "领导会欣赏你的得体选择",
        },
        "同事": {
            "高心意": "同事会为你的贴心感到温暖",
            "高惊喜": "这份惊喜会让同事感到意外和开心",
            "高性价比": "同事会欣赏你的用心选择",
        },
        "客户": {
            "高心意": "客户会感受到你的诚意和重视",
            "高性价比": "客户会欣赏你的专业与用心",
        },
        "老师": {
            "高心意": "老师会感受到你的感恩之心",
            "高惊喜": "这份惊喜会让老师感到欣慰",
            "高性价比": "老师会为你的贴心感到欣慰",
        },
        
        # 默认
        "default": {
            "默认": "收礼人一定会感受到你的心意",
        },
    }

    # 场合模板
    OCCASION_TEMPLATES = {
        "生日": {
            "高心意": "在生日这个特别的日子，这份礼物满载祝福",
            "高惊喜": "生日惊喜，让这一天更加难忘",
            "高性价比": "实用的生日礼物，贴心又周到",
        },
        "情人节": {
            "高心意": "情人节最好的表达，是满满的爱意",
            "高惊喜": "情人节的浪漫惊喜，让爱更甜蜜",
            "高性价比": "情人节礼物，用心而不铺张",
        },
        "纪念日": {
            "高心意": "纪念日礼物，珍藏美好回忆",
            "高惊喜": "纪念日的惊喜，让这一天更特别",
            "高性价比": "纪念日礼物，实惠又有心意",
        },
        "结婚纪念日": {
            "高心意": "结婚纪念日的珍贵礼物，见证幸福时光",
            "高惊喜": "结婚纪念日的惊喜，重温甜蜜时光",
        },
        "母亲节": {
            "高心意": "母亲节礼物，表达对妈妈的爱与感恩",
            "高性价比": "母亲节实用礼物，贴心关怀妈妈",
        },
        "父亲节": {
            "高心意": "父亲节礼物，表达对爸爸的敬重与感恩",
            "高性价比": "父亲节实用礼物，贴心关怀爸爸",
        },
        "春节": {
            "高心意": "春节礼物，传递新年的祝福与温暖",
            "高性价比": "春节实惠礼物，传统又贴心",
        },
        "圣诞节": {
            "高心意": "圣诞礼物，传递节日的温暖与祝福",
            "高惊喜": "圣诞惊喜礼物，让节日更有气氛",
        },
        "商务": {
            "高心意": "商务礼物，体现专业与诚意",
            "高性价比": "商务礼物，得体又不失体面",
        },
        "道歉": {
            "高心意": "道歉礼物，表达你的诚意与悔意",
        },
        "表白": {
            "高心意": "表白礼物，传达你的真挚情感",
            "高惊喜": "表白惊喜，让这一刻更加难忘",
        },
        "婚礼": {
            "高心意": "婚礼礼物，祝福新人百年好合",
            "高性价比": "婚礼实用礼物，贴心又周到",
        },
        "乔迁": {
            "高心意": "乔迁礼物，祝贺新居之喜",
            "高性价比": "乔迁实用礼物，贴心又实用",
        },
        "看望": {
            "高心意": "看望礼物，表达你的关怀与问候",
            "高性价比": "看望实用礼物，贴心关怀",
        },
        "default": {
            "默认": "适合这个特殊时刻的礼物",
        },
    }

    def generate(
        self,
        gift: Dict,
        relation: Optional[str] = None,
        occasion: Optional[str] = None,
        max_length: int = 100
    ) -> str:
        """
        生成个性化推荐理由
        
        Args:
            gift: 礼物信息（包含评分）
            relation: 收礼人关系
            occasion: 场合
            max_length: 最大长度
            
        Returns:
            推荐理由文本
        """
        reasons = []
        
        # 获取评分信息
        scores = gift.get("scores", {})
        final_score = gift.get("final_score", 0)
        style = gift.get("scenario_style", "")
        
        # 1. 礼物本身的理由
        if gift.get("reason"):
            reasons.append(gift["reason"])
        
        # 2. 基于评分生成理由
        score_reason = self._generate_score_based_reason(
            scores, style, relation, occasion
        )
        if score_reason:
            reasons.append(score_reason)
        
        # 3. 关系理由
        if relation:
            relation_reason = self._get_relation_reason(relation, scores)
            if relation_reason:
                reasons.append(relation_reason)
        
        # 4. 场合理由
        if occasion:
            occasion_reason = self._get_occasion_reason(occasion, scores)
            if occasion_reason:
                reasons.append(occasion_reason)
        
        # 5. 综合评价
        if final_score >= 75:
            reasons.append("综合评分优秀，是理想的选择")
        elif final_score >= 60:
            reasons.append("综合表现良好，值得考虑")
        
        # 组合理由
        result = "；".join(reasons) if reasons else "这是一份用心挑选的礼物"
        
        # 限制长度
        if len(result) > max_length:
            result = result[:max_length - 3] + "..."
        
        return result

    def _generate_score_based_reason(
        self,
        scores: Dict,
        style: str,
        relation: Optional[str],
        occasion: Optional[str]
    ) -> Optional[str]:
        """基于评分生成理由"""
        if not scores:
            return None
        
        surprise_score = scores.get("surprise", 0)
        value_score = scores.get("value", 0)
        sentiment_score = scores.get("sentiment", 0)
        
        # 找出最高分的维度
        max_score = max(surprise_score, value_score, sentiment_score)
        
        # 根据最高分维度选择理由
        if max_score == surprise_score and surprise_score >= 70:
            style_reason = self._get_style_reason(style, "高惊喜")
            if style_reason:
                return style_reason
            return "惊喜度十足，让人眼前一亮"
        
        elif max_score == value_score and value_score >= 70:
            style_reason = self._get_style_reason(style, "高性价比")
            if style_reason:
                return style_reason
            return "性价比出色，实用又贴心"
        
        elif max_score == sentiment_score and sentiment_score >= 70:
            style_reason = self._get_style_reason(style, "高心意")
            if style_reason:
                return style_reason
            return "心意满满，表达真挚情感"
        
        # 如果没有特别突出的维度，使用风格理由
        return self._get_style_reason(style, "默认")

    def _get_style_reason(self, style: str, score_type: str) -> Optional[str]:
        """获取风格相关的理由"""
        style_templates = self.STYLE_TEMPLATES.get(style, self.STYLE_TEMPLATES["default"])
        return style_templates.get(score_type) or style_templates.get("默认")

    def _get_relation_reason(self, relation: str, scores: Dict) -> Optional[str]:
        """获取关系相关的理由"""
        # 精确匹配
        if relation in self.RELATION_TEMPLATES:
            templates = self.RELATION_TEMPLATES[relation]
            return self._select_template_by_score(templates, scores)
        
        # 模糊匹配
        for key, templates in self.RELATION_TEMPLATES.items():
            if key in relation or relation in key:
                return self._select_template_by_score(templates, scores)
        
        # 默认
        default_templates = self.RELATION_TEMPLATES.get("default", {})
        return default_templates.get("默认")

    def _get_occasion_reason(self, occasion: str, scores: Dict) -> Optional[str]:
        """获取场合相关的理由"""
        # 精确匹配
        if occasion in self.OCCASION_TEMPLATES:
            templates = self.OCCASION_TEMPLATES[occasion]
            return self._select_template_by_score(templates, scores)
        
        # 模糊匹配
        for key, templates in self.OCCASION_TEMPLATES.items():
            if key in occasion or occasion in key:
                return self._select_template_by_score(templates, scores)
        
        # 默认
        default_templates = self.OCCASION_TEMPLATES.get("default", {})
        return default_templates.get("默认")

    def _select_template_by_score(self, templates: Dict, scores: Dict) -> Optional[str]:
        """根据评分选择模板"""
        if not scores:
            return list(templates.values())[0] if templates else None
        
        surprise_score = scores.get("surprise", 0)
        value_score = scores.get("value", 0)
        sentiment_score = scores.get("sentiment", 0)
        
        # 根据最高分维度选择
        if surprise_score >= sentiment_score and surprise_score >= value_score:
            return templates.get("高惊喜") or templates.get("默认")
        elif value_score >= sentiment_score:
            return templates.get("高性价比") or templates.get("默认")
        else:
            return templates.get("高心意") or templates.get("默认")

    def generate_score_summary(self, gift: Dict) -> str:
        """
        生成评分摘要
        
        Args:
            gift: 礼物信息（包含评分）
            
        Returns:
            评分摘要文本
        """
        scores = gift.get("scores", {})
        final_score = gift.get("final_score", 0)
        
        if not scores:
            return f"综合评分：{final_score}分"
        
        surprise = scores.get("surprise", 0)
        value = scores.get("value", 0)
        sentiment = scores.get("sentiment", 0)
        
        summary_parts = [f"综合评分：{final_score}分"]
        
        # 添加各维度评分
        dimension_texts = []
        
        if surprise >= 70:
            dimension_texts.append(f"惊喜度{surprise}分⭐")
        elif surprise >= 60:
            dimension_texts.append(f"惊喜度{surprise}分")
            
        if value >= 70:
            dimension_texts.append(f"性价比{value}分💰")
        elif value >= 60:
            dimension_texts.append(f"性价比{value}分")
            
        if sentiment >= 70:
            dimension_texts.append(f"心意指数{sentiment}分❤️")
        elif sentiment >= 60:
            dimension_texts.append(f"心意指数{sentiment}分")
        
        if dimension_texts:
            summary_parts.append(" | ".join(dimension_texts))
        
        return "，".join(summary_parts)

    def generate_recommendation_summary(self, gifts: List[Dict]) -> str:
        """
        生成推荐列表摘要
        
        Args:
            gifts: 推荐礼物列表
            
        Returns:
            摘要文本
        """
        if not gifts:
            return "暂无推荐"
        
        # 统计特点
        avg_score = sum(g.get("final_score", 0) for g in gifts) / len(gifts)
        high_surprise_count = sum(1 for g in gifts if g.get("scores", {}).get("surprise", 0) >= 70)
        high_value_count = sum(1 for g in gifts if g.get("scores", {}).get("value", 0) >= 70)
        high_sentiment_count = sum(1 for g in gifts if g.get("scores", {}).get("sentiment", 0) >= 70)
        
        parts = [f"共推荐{len(gifts)}个礼物，平均评分{avg_score:.1f}分"]
        
        features = []
        if high_surprise_count > 0:
            features.append(f"{high_surprise_count}个惊喜度突出")
        if high_value_count > 0:
            features.append(f"{high_value_count}个性价比优秀")
        if high_sentiment_count > 0:
            features.append(f"{high_sentiment_count}个心意指数满分")
        
        if features:
            parts.append("，其中" + "、".join(features))
        
        return "".join(parts)
