"""
API入口 2.0 - 集成优化版
集成了新开发的3个核心模块：
1. GiftFilterV2 - 增强禁忌过滤
2. BlessingGeneratorV2 - 个性化祝福语
3. DialogManager - 对话式决策支持
"""
from typing import List, Dict, Optional, Tuple
from .recommender import Recommender
from .parser import InputParser
from .reason import ReasonGenerator
from .blessing_v2 import BlessingGeneratorV2
from .filter_v2 import GiftFilterV2
from .dialog_manager import DialogManager
import json

class GiftAdvisorV2:
    """礼物推荐助手 2.0 - 集成优化版"""

    def __init__(self, user_id: str = "default"):
        # 核心模块
        self.recommender = Recommender()
        self.parser = InputParser()
        self.reason_gen = ReasonGenerator()
        
        # 新模块
        self.blessing_gen = BlessingGeneratorV2()
        self.filter_v2 = GiftFilterV2()
        self.dialog = DialogManager()
        
        # 用户状态
        self.user_id = user_id
        self.conversation_context = {
            "user_id": user_id,
            "preferences": {},
            "conversation_mode": "auto",  # auto/dialog/direct
            "current_state": "initial",
            "last_recommendations": []
        }

    def process_message(self, user_input: str) -> Dict:
        """
        处理用户消息（对话式入口）
        
        Args:
            user_input: 用户输入文本
            
        Returns:
            处理结果，包含回复和推荐
        """
        # 1. 对话管理器处理
        response, dialog_state = self.dialog.process_message(user_input)
        
        # 2. 更新对话上下文
        self.conversation_context["current_state"] = dialog_state["state"]
        self.conversation_context["preferences"] = dialog_state["preferences"]
        
        # 3. 根据状态决定是否生成推荐
        result = self._generate_response_based_on_state(response, dialog_state)
        
        # 4. 添加对话状态信息
        result["dialog_state"] = {
            "state": dialog_state["state"],
            "emotion": dialog_state["analysis"].get("emotion"),
            "intent": dialog_state["analysis"].get("intent")
        }
        
        # 5. 保存最后推荐（用于后续对话）
        if "recommendations" in result:
            self.conversation_context["last_recommendations"] = result["recommendations"]
        
        return result

    def _generate_response_based_on_state(self, response: str, dialog_state: Dict) -> Dict:
        """根据对话状态生成响应"""
        state = dialog_state["state"]
        
        if state == "ready_to_recommend":
            # 生成推荐
            return self._generate_recommendation_with_dialog_context()
        elif state == "waiting_feedback":
            # 询问反馈
            return {
                "success": True,
                "needs_feedback": True,
                "message": response,
                "type": "feedback_request"
            }
        elif state in ["initial", "basic_info_collected", "preference_known"]:
            # 继续对话
            return {
                "success": True,
                "message": response,
                "type": "question",
                "missing_info": self._get_missing_info(dialog_state["preferences"])
            }
        else:
            # 其他状态
            return {
                "success": True,
                "message": response,
                "type": "response"
            }

    def _generate_recommendation_with_dialog_context(self) -> Dict:
        """基于对话上下文生成推荐"""
        preferences = self.conversation_context["preferences"]
        
        # 提取参数
        relation = preferences.get("relation")
        occasion = preferences.get("occasion")
        budget_min = preferences.get("budget_min")
        budget_max = preferences.get("budget_max")
        interests = preferences.get("interests", [])
        style = preferences.get("style")
        
        # 获取推荐
        gifts = self.recommender.recommend(
            relation=relation,
            occasion=occasion,
            budget_min=budget_min,
            budget_max=budget_max,
            limit=10
        )
        
        # 应用增强禁忌过滤
        filtered_gifts, taboo_report = self.filter_v2.filter(
            gifts=gifts,
            relation=relation,
            region=preferences.get("region"),
            religion=preferences.get("religion")
        )
        
        # 如果过滤后礼物太少，放宽过滤
        if len(filtered_gifts) < 3:
            filtered_gifts = gifts[:5]  # 使用原始推荐
        
        # 限制数量
        filtered_gifts = filtered_gifts[:5]
        
        # 生成推荐结果
        recommendations = []
        for gift in filtered_gifts:
            # 生成推荐理由
            reason = self.reason_gen.generate(gift, relation, occasion)
            
            # 计算分数
            score = self._calculate_enhanced_score(gift, preferences)
            
            recommendations.append({
                "name": gift.get("name"),
                "price": gift.get("price"),
                "reason": reason,
                "score": score,
                "original_reason": gift.get("reason", "")
            })
        
        # 按分数排序
        recommendations.sort(key=lambda x: x["score"], reverse=True)
        
        # 生成个性化祝福语
        blessing_options = self.blessing_gen.generate_multiple_options(
            occasion=occasion,
            relation=relation,
            count=3
        )
        
        # 选择最高分礼物的祝福语
        if recommendations:
            top_gift_name = recommendations[0]["name"]
            personalized_blessing = self.blessing_gen.generate(
                occasion=occasion,
                relation=relation,
                gift_name=top_gift_name,
                style="深情版"
            )
        else:
            personalized_blessing = self.blessing_gen.generate(occasion)
        
        # 构建结果
        result = {
            "success": True,
            "query": {
                "relation": relation,
                "occasion": occasion,
                "budget": f"{budget_min or '?'}-{budget_max or '?'}元",
                "interests": interests,
                "style": style
            },
            "recommendations": recommendations,
            "blessing": {
                "personalized": personalized_blessing,
                "options": blessing_options
            },
            "taboo_report": {
                "summary": taboo_report.get("summary", "✅ 无禁忌礼物"),
                "warnings": taboo_report.get("warnings", []),
                "suggestions": taboo_report.get("suggestions", [])
            },
            "dialog_context": {
                "state": self.conversation_context["current_state"],
                "preferences_summary": self._create_preferences_summary(preferences)
            },
            "count": len(recommendations),
            "type": "recommendation"
        }
        
        return result

    def _calculate_enhanced_score(self, gift: Dict, preferences: Dict) -> int:
        """计算增强版分数"""
        score = 80  # 基础分
        
        # 预算匹配度
        price = gift.get("price", 0)
        budget_max = preferences.get("budget_max")
        if budget_max:
            ratio = price / budget_max
            if 0.3 <= ratio <= 0.7:
                score += 10  # 理想价格区间
            elif ratio <= 0.9:
                score += 5   # 可接受价格
            elif ratio > 1:
                score -= 10  # 超出预算
        
        # 风格匹配度
        style = preferences.get("style")
        gift_reason = gift.get("reason", "").lower()
        
        style_keywords = {
            "实用型": ["实用", "方便", "必需", "日常", "工具"],
            "浪漫型": ["浪漫", "温馨", "爱", "甜蜜", "惊喜"],
            "惊喜型": ["惊喜", "创意", "独特", "新颖", "特别"],
            "传统型": ["传统", "经典", "正式", "体面", "尊重"]
        }
        
        if style and style in style_keywords:
            for keyword in style_keywords[style]:
                if keyword in gift_reason:
                    score += 5
                    break
        
        # 兴趣匹配度
        interests = preferences.get("interests", [])
        gift_name = gift.get("name", "").lower()
        
        interest_keywords = {
            "运动": ["运动", "健身", "跑步", "瑜伽", "球类"],
            "音乐": ["音乐", "耳机", "音响", "乐器", "唱片"],
            "阅读": ["书籍", "阅读", "书签", "书灯", "书架"],
            "美食": ["美食", "烹饪", "厨房", "餐具", "调料"],
            "旅行": ["旅行", "行李箱", "背包", "相机", "导航"]
        }
        
        for interest in interests:
            if interest in interest_keywords:
                for keyword in interest_keywords[interest]:
                    if keyword in gift_name:
                        score += 8
                        break
        
        # 限制分数范围
        return max(10, min(100, score))

    def _get_missing_info(self, preferences: Dict) -> List[str]:
        """获取缺失的信息"""
        missing = []
        
        if not preferences.get("relation"):
            missing.append("收礼人关系")
        if not preferences.get("occasion"):
            missing.append("场合")
        if not preferences.get("budget_min"):
            missing.append("预算范围")
        
        return missing

    def _create_preferences_summary(self, preferences: Dict) -> str:
        """创建偏好摘要"""
        parts = []
        
        if preferences.get("relation"):
            parts.append(f"送给：{preferences['relation']}")
        if preferences.get("occasion"):
            parts.append(f"场合：{preferences['occasion']}")
        if preferences.get("budget_min") or preferences.get("budget_max"):
            budget = f"{preferences.get('budget_min', '?')}-{preferences.get('budget_max', '?')}元"
            parts.append(f"预算：{budget}")
        if preferences.get("interests"):
            parts.append(f"兴趣：{', '.join(preferences['interests'])}")
        if preferences.get("style"):
            parts.append(f"风格：{preferences['style']}")
        
        return " | ".join(parts)

    def direct_recommend(
        self,
        relation: str = None,
        occasion: str = None,
        budget_min: int = None,
        budget_max: int = None,
        style: str = None,
        interests: List[str] = None,
        limit: int = 5
    ) -> Dict:
        """
        直接推荐（非对话式）
        
        Args:
            参数同上
            
        Returns:
            推荐结果
        """
        # 构建偏好
        preferences = {
            "relation": relation,
            "occasion": occasion,
            "budget_min": budget_min,
            "budget_max": budget_max,
            "style": style,
            "interests": interests or []
        }
        
        # 更新对话上下文
        self.conversation_context["preferences"] = preferences
        
        # 生成推荐
        return self._generate_recommendation_with_dialog_context()

    def explain_taboo(self, gift_name: str, relation: str = None) -> Dict:
        """
        解释礼物禁忌
        
        Args:
            gift_name: 礼物名称
            relation: 收礼人关系
            
        Returns:
            禁忌解释
        """
        explanation = self.filter_v2.explain_taboo(gift_name, relation)
        alternatives = self.filter_v2.get_safe_alternatives(gift_name)
        
        return {
            "success": True,
            "gift_name": gift_name,
            "explanation": explanation,
            "alternatives": alternatives,
            "has_taboo": bool(explanation and "暂无发现禁忌" not in explanation)
        }

    def get_blessing_options(
        self,
        occasion: str,
        relation: str = None,
        gift_name: str = None,
        count: int = 3
    ) -> Dict:
        """
        获取祝福语选项
        
        Args:
            occasion: 场合
            relation: 关系
            gift_name: 礼物名称
            count: 选项数量
            
        Returns:
            祝福语选项
        """
        options = self.blessing_gen.generate_multiple_options(
            occasion=occasion,
            relation=relation,
            gift_name=gift_name,
            count=count
        )
        
        # 添加方言选项示例
        dialect_examples = []
        for dialect in ["粤语", "四川话", "上海话"]:
            dialect_blessing = self.blessing_gen.generate(
                occasion=occasion,
                relation=relation,
                gift_name=gift_name,
                dialect=dialect
            )
            dialect_examples.append(f"{dialect}：{dialect_blessing}")
        
        return {
            "success": True,
            "occasion": occasion,
            "relation": relation,
            "gift_name": gift_name,
            "standard_options": options,
            "dialect_examples": dialect_examples,
            "gift_specific": gift_name and self.blessing_gen.generate_for_gift_type(
                self._detect_gift_type(gift_name), relation, occasion
            )
        }

    def _detect_gift_type(self, gift_name: str) -> str:
        """检测礼物类型"""
        gift_types = {
            "鲜花": ["花", "玫瑰", "百合", "康乃馨"],
            "巧克力": ["巧克力", "糖果", "甜食"],
            "书籍": ["书", "书籍", "绘本", "杂志"],
            "珠宝": ["珠宝", "首饰", "项链", "戒指", "手链"],
            "电子产品": ["电子", "智能", "手机", "耳机", "手表"],
            "茶叶": ["茶叶", "茶", "茶具", "茶包"],
            "化妆品": ["化妆", "口红", "香水", "护肤品"],
            "家居": ["家居", "装饰", "摆件", "灯具"]
        }
        
        for type_name, keywords in gift_types.items():
            for keyword in keywords:
                if keyword in gift_name:
                    return type_name
        
        return "通用"

    def reset_conversation(self):
        """重置对话"""
        self.dialog.reset_conversation()
        self.conversation_context = {
            "user_id": self.user_id,
            "preferences": {},
            "conversation_mode": "auto",
            "current_state": "initial",
            "last_recommendations": []
        }
        
        return {
            "success": True,
            "message": "对话已重置，重新开始吧！"
        }


# 便捷函数
def process_message_v2(user_input: str, user_id: str = "default") -> Dict:
    """
    处理用户消息（便捷函数）
    
    示例:
        result = process_message_v2("我想给妈妈选生日礼物，预算500元")
    """
    advisor = GiftAdvisorV2(user_id=user_id)
    return advisor.process_message(user_input)

def direct_recommend_v2(
    relation: str = None,
    occasion: str = None,
    budget_min: int = None,
    budget_max: int = None,
    style: str = None,
    interests: List[str] = None,
    user_id: str = "default"
) -> Dict:
    """
    直接推荐（便捷函数）
    
    示例:
        result = direct_recommend_v2("妈妈", "生日", 200, 1000, "实用型", ["养生"])
    """
    advisor = GiftAdvisorV2(user_id=user_id)
    return advisor.direct_recommend(
        relation=relation,
        occasion=occasion,
        budget_min=budget_min,
        budget_max=budget_max,
        style=style,
        interests=interests
    )


# 测试函数
def test_integration():
    """测试集成功能"""
    print("=== Gift Advisor 2.0 集成测试 ===\n")
    
    advisor = GiftAdvisorV2()
    
    # 测试1：对话式推荐
    print("测试1：对话式推荐")
    print("用户：我想给妈妈选生日礼物")
    result1 = advisor.process_message("我想给妈妈选生日礼物")
    print(f"助手：{result1.get('message', '')[:100]}...")
    
    print("\n用户：预算500元左右")
    result2 = advisor.process_message("预算500元左右")
    print(f"助手：{result2.get('message', '')[:100]}...")
    
    print("\n用户：她喜欢养花")
    result3 = advisor.process_message("她喜欢养花")
    print(f"助手：{result3.get('message', '')[:100]}...")
    
    # 测试2：直接推荐
    print("\n\n测试2：直接推荐")
    direct_result = advisor.direct_recommend(
        relation="女友",
        occasion="情人节",
        budget_min=300,
        budget_max=2000,
        style="浪漫型",
        interests=["音乐", "美食"]
    )
    
    if direct_result["success"]:
        print(f"查询：{direct_result['query']}")
        print(f"推荐数量：{direct_result['count']}")
        print(f"禁忌报告：{direct_result['taboo_report']['summary']}")
        
        if direct_result['recommendations']:
            print("\nTop推荐：")
            for i, rec in enumerate(direct_result['recommendations'][:3], 1):
                print(f"{i}. {rec['name']}（{rec['price']}元）- {rec['reason'][:30]}... - 评分：{rec['score']}")
        
        print(f"\n祝福语：{direct_result['blessing']['personalized']}")
    
    # 测试3：禁忌解释
    print("\n\n测试3：禁忌解释")
    taboo_result = advisor.explain_taboo("精美时钟", "长辈")
    print(f"礼物：{taboo_result['gift_name']}")
    print(f"禁忌：{taboo_result['explanation']}")
    if taboo_result['alternatives']:
        print(f"替代品：{', '.join(taboo_result['alternatives'][:3])}")
    
    # 测试4：祝福语选项
    print("\n\n测试4：祝福语选项")
    blessing_result = advisor.get_blessing_options(
        occasion="生日",
        relation="妈妈",
        gift_name="鲜花",
        count=3
    )
    print(f"场合：{blessing_result['occasion']}")
    print(f"关系：{blessing_result['relation']}")
    print("标准选项：")
    for option in blessing_result['standard_options']:
        print(f"  • {option}")
    
    return {
        "advisor": advisor,
        "results": [result1, result2, result3, direct_result, taboo_result, blessing_result]
    }


if __name__ == "__main__":
    test_integration()