"""智能关怀方案生成系统"""

import pandas as pd
import numpy as np
import joblib
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from typing import Dict, List, Tuple, Optional
import json
from pathlib import Path
import asyncio
import requests
import time

# 问题分类体系
PROBLEM_CLASSIFICATION = {
    "服务类": {
        "餐食": ["food", "meal", "dinner", "lunch", "breakfast", "snack", "beverage", "drink"],
        "服务态度": ["service", "staff", "crew", "attitude", "rude", "friendly", "helpful"],
        "登机": ["boarding", "check-in", "boarding pass", "gate"],
        "行李服务": ["baggage", "luggage", "suitcase", "lost", "delayed", "damaged"],
        "客服支持": ["support", "customer service", "help", "assistance", "contact"]
    },
    "硬件类": {
        "座位": ["seat", "comfort", "legroom", "space", "cushion"],
        "设施": ["facility", "entertainment", "screen", "wifi", "power", "charging"],
        "飞机状况": ["plane", "aircraft", "clean", "maintenance", "condition"]
    },
    "流程类": {
        "延误": ["delay", "late", "delayed", "on time", "schedule", "timely"],
        "取消": ["cancel", "cancelled", "cancellation"],
        "改签": ["reschedule", "change", "modify", "reroute"],
        "超售": ["oversold", "overbooked"],
        "中转": ["connection", "transfer", "layover"]
    }
}

# 用户类型定义
USER_TYPES = {
    "效率型": {"准时": 0.3, "快速处理": 0.3, "便捷": 0.2, "信息透明": 0.2},
    "舒适型": {"座位": 0.3, "餐食": 0.2, "休息室": 0.2, "设施": 0.3},
    "经济型": {"补偿": 0.3, "性价比": 0.4, "优惠": 0.3},
    "情感型": {"态度": 0.3, "尊重": 0.2, "沟通": 0.3, "个性化": 0.2}
}

# DeepSeek API配置
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"


def call_deepseek_api(prompt: str, max_tokens: int = 500, temperature: float = 0.7) -> Optional[str]:
    """调用DeepSeek大模型API"""
    import time
    import requests
    
    # 检查API Key是否配置
    if not DEEPSEEK_API_KEY:
        print("DeepSeek API密钥未配置，返回模拟响应")
        # 返回模拟响应
        if "问题分类" in prompt:
            return json.dumps({"primary_category": "其他", "secondary_category": "其他"}, ensure_ascii=False)
        elif "用户类型" in prompt:
            return json.dumps({
                "main_type": "效率型",
                "type_probabilities": {"效率型": 0.6, "舒适型": 0.2, "经济型": 0.1, "情感型": 0.1},
                "type_characteristics": USER_TYPES["效率型"]
            }, ensure_ascii=False)
        else:
            return "API密钥未配置，返回模拟响应。这是一个智能生成的关怀方案描述。"
    
    max_retries = 3
    retry_delay = 2
    timeout = 60  # 增加超时时间到60秒
    
    for retry in range(max_retries):
        try:
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {DEEPSEEK_API_KEY}"
            }
            
            payload = {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "system", "content": "你是一个智能客服专家，专注于航空公司的服务关怀方案生成。"},
                    {"role": "user", "content": prompt}
                ],
                "max_tokens": max_tokens,
                "temperature": temperature
            }
            
            print(f"正在第{retry+1}次调用DeepSeek API...")
            response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload, timeout=timeout)
            response.raise_for_status()
            
            result = response.json()
            return result["choices"][0]["message"]["content"].strip()
        
        except requests.exceptions.RequestException as e:
            print(f"DeepSeek API调用失败: {e}")
            if retry < max_retries - 1:
                print(f"将在{retry_delay}秒后重试...")
                time.sleep(retry_delay)
                retry_delay *= 1.5  # 指数退避
            else:
                print("已达到最大重试次数，调用失败。")
                return None
        except (KeyError, ValueError) as e:
            print(f"DeepSeek API响应解析失败: {e}")
            return None
        except Exception as e:
            print(f"DeepSeek API未知错误: {e}")
            return None


class ProblemDiscoveryModule:
    """问题发现模块：分析推文数据，自动聚类常见问题类型"""
    
    def __init__(self):
        self.vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
        self.cluster_model = KMeans(n_clusters=10, random_state=42)
        self.topic_model = LatentDirichletAllocation(n_components=10, random_state=42)
    
    def analyze_tweets(self, tweets: List[str]) -> Dict:
        """分析推文数据，发现问题类型"""
        # 文本向量化
        tfidf_matrix = self.vectorizer.fit_transform(tweets)
        
        # 聚类分析
        clusters = self.cluster_model.fit_predict(tfidf_matrix)
        
        # 主题建模
        self.topic_model.fit(tfidf_matrix)
        
        # 提取关键词
        feature_names = self.vectorizer.get_feature_names_out()
        top_words_per_topic = []
        for topic_idx, topic in enumerate(self.topic_model.components_):
            top_words = [feature_names[i] for i in topic.argsort()[:-11:-1]]
            top_words_per_topic.append({
                "topic_id": topic_idx,
                "top_words": top_words,
                "count": np.sum(clusters == topic_idx)
            })
        
        return {
            "clusters": clusters.tolist(),
            "topics": top_words_per_topic,
            "total_tweets": len(tweets)
        }
    
    def classify_problem(self, tweet: str) -> Dict:
        """对单条推文进行问题分类"""
        tweet_lower = tweet.lower()
        primary_category = "其他"
        secondary_category = "其他"
        
        # 首先使用关键词匹配进行初步分类
        for primary, secondaries in PROBLEM_CLASSIFICATION.items():
            for secondary, keywords in secondaries.items():
                if any(keyword in tweet_lower for keyword in keywords):
                    primary_category = primary
                    secondary_category = secondary
                    break
            if primary_category != "其他":
                break
        
        # 如果初步分类为"其他"，使用DeepSeek进行更精确的分类
        if primary_category == "其他":
            prompt = f"请将以下推文分类到合适的问题类别中。分类体系包括：\n{json.dumps(PROBLEM_CLASSIFICATION, ensure_ascii=False, indent=2)}\n\n推文：{tweet}\n\n请返回JSON格式的结果，包含primary_category（一级分类）和secondary_category（二级分类）两个字段。"
            
            deepseek_result = call_deepseek_api(prompt, max_tokens=200, temperature=0.1)
            
            if deepseek_result:
                try:
                    result = json.loads(deepseek_result)
                    primary_category = result.get("primary_category", "其他")
                    secondary_category = result.get("secondary_category", "其他")
                except json.JSONDecodeError:
                    # 如果解析失败，使用初步分类结果
                    pass
        
        return {
            "primary_category": primary_category,
            "secondary_category": secondary_category
        }
    
    def analyze_problem_associations(self, tweets: List[str]) -> List[Dict]:
        """分析问题之间的关联性"""
        # 对每条推文进行分类
        classified_tweets = [self.classify_problem(tweet) for tweet in tweets]
        df_classified = pd.DataFrame(classified_tweets)
        
        # 计算二级分类的共现矩阵
        category_pairs = []
        for i in range(len(tweets)):
            for j in range(i+1, len(tweets)):
                if (df_classified.iloc[i]['primary_category'] == df_classified.iloc[j]['primary_category'] and
                    df_classified.iloc[i]['secondary_category'] != df_classified.iloc[j]['secondary_category']):
                    pair = sorted([df_classified.iloc[i]['secondary_category'], df_classified.iloc[j]['secondary_category']])
                    category_pairs.append(tuple(pair))
        
        # 计算共现频率
        pair_counts = pd.Series(category_pairs).value_counts().reset_index()
        pair_counts.columns = ['category_pair', 'count']
        
        # 生成关联规则
        associations = []
        for _, row in pair_counts.iterrows():
            if row['count'] > 1:
                associations.append({
                    "categories": list(row['category_pair']),
                    "count": row['count'],
                    "confidence": row['count'] / len(tweets)
                })
        
        return sorted(associations, key=lambda x: x['count'], reverse=True)[:10]


class SmartQuestionnaireSystem:
    """智能问卷系统：生成自适应问卷，测量偏好强度"""
    
    def __init__(self):
        self.questionnaire_templates = {
            "primary": [
                {"id": "q1", "text": "请为以下服务方面评分（1-5分）：", "type": "ratings", "sub_questions": [
                    {"id": "q1_punctuality", "text": "航班准时性", "type": "rating", "min": 1, "max": 5},
                    {"id": "q1_comfort", "text": "服务舒适性", "type": "rating", "min": 1, "max": 5},
                    {"id": "q1_economy", "text": "价格经济性", "type": "rating", "min": 1, "max": 5},
                    {"id": "q1_attitude", "text": "服务人员态度", "type": "rating", "min": 1, "max": 5}
                ]},
                {"id": "q2", "text": "您对航班延误的容忍度如何？", "type": "rating", "min": 1, "max": 5},
                {"id": "q3", "text": "您希望航空公司如何与您沟通服务问题？", "type": "multiple", "options": ["短信", "邮件", "电话", "APP推送"]}
            ],
            "efficiency": [
                {"id": "eq1", "text": "您认为快速处理问题的重要性？", "type": "rating", "min": 1, "max": 5},
                {"id": "eq2", "text": "您是否重视航班信息的实时更新？", "type": "rating", "min": 1, "max": 5}
            ],
            "comfort": [
                {"id": "cq1", "text": "座位舒适度对您的重要性？", "type": "rating", "min": 1, "max": 5},
                {"id": "cq2", "text": "您是否关注机上餐食质量？", "type": "rating", "min": 1, "max": 5}
            ],
            "economic": [
                {"id": "ecq1", "text": "您对补偿方案的关注度？", "type": "rating", "min": 1, "max": 5},
                {"id": "ecq2", "text": "您是否重视航班的性价比？", "type": "rating", "min": 1, "max": 5}
            ],
            "emotional": [
                {"id": "emq1", "text": "服务人员态度对您的影响？", "type": "rating", "min": 1, "max": 5},
                {"id": "emq2", "text": "您是否希望获得个性化服务？", "type": "rating", "min": 1, "max": 5}
            ]
        }
    
    def generate_initial_questionnaire(self) -> List[Dict]:
        """生成初始问卷"""
        return self.questionnaire_templates["primary"]
    
    def generate_adaptive_questions(self, user_responses: Dict) -> List[Dict]:
        """根据用户初步选择动态调整后续问题"""
        adaptive_questions = []
        
        # 根据q1的回答生成相应类型的问题
        if "q1" in user_responses:
            response = user_responses["q1"]
            # 如果是新的评分字典格式
            if isinstance(response, dict) and response:
                # 获取评分高于3分的服务方面（表示用户比较关注的）
                high_priority_aspects = [aspect for aspect, score in response.items() if score > 3]
                
                # 为每个高优先级服务方面生成相应的问题
                for aspect in high_priority_aspects:
                    if aspect == "准时性":
                        adaptive_questions.extend(self.questionnaire_templates["efficiency"])
                    elif aspect == "舒适性":
                        adaptive_questions.extend(self.questionnaire_templates["comfort"])
                    elif aspect == "经济性":
                        adaptive_questions.extend(self.questionnaire_templates["economic"])
                    elif aspect == "服务态度":
                        adaptive_questions.extend(self.questionnaire_templates["emotional"])
                
                # 如果没有评分高于3分的，为评分最高的2个服务方面生成问题
                if not high_priority_aspects:
                    # 按评分降序排序
                    sorted_aspects = sorted(response.items(), key=lambda x: x[1], reverse=True)[:2]
                    for aspect, _ in sorted_aspects:
                        if aspect == "准时性":
                            adaptive_questions.extend(self.questionnaire_templates["efficiency"])
                        elif aspect == "舒适性":
                            adaptive_questions.extend(self.questionnaire_templates["comfort"])
                        elif aspect == "经济性":
                            adaptive_questions.extend(self.questionnaire_templates["economic"])
                        elif aspect == "服务态度":
                            adaptive_questions.extend(self.questionnaire_templates["emotional"])
            # 兼容旧格式
            elif isinstance(response, str) and response:
                if response == "准时性":
                    adaptive_questions.extend(self.questionnaire_templates["efficiency"])
                elif response == "舒适性":
                    adaptive_questions.extend(self.questionnaire_templates["comfort"])
                elif response == "经济性":
                    adaptive_questions.extend(self.questionnaire_templates["economic"])
                elif response == "服务态度":
                    adaptive_questions.extend(self.questionnaire_templates["emotional"])
            # 兼容旧格式
            elif isinstance(response, list) and response:
                for choice in response:
                    if choice == "准时性":
                        adaptive_questions.extend(self.questionnaire_templates["efficiency"])
                    elif choice == "舒适性":
                        adaptive_questions.extend(self.questionnaire_templates["comfort"])
                    elif choice == "经济性":
                        adaptive_questions.extend(self.questionnaire_templates["economic"])
                    elif choice == "服务态度":
                        adaptive_questions.extend(self.questionnaire_templates["emotional"])
        
        return adaptive_questions


class UserPreferenceAnalyzer:
    """用户偏好分析引擎：识别偏好模式，计算权重"""
    
    def __init__(self):
        self.scaler = MinMaxScaler()
    
    def identify_user_type(self, preferences: Dict) -> Dict:
        """识别用户类型"""
        # 计算与各用户类型的相似度
        similarities = {}
        for user_type, type_weights in USER_TYPES.items():
            similarity = 0
            for key, weight in type_weights.items():
                if key in preferences:
                    similarity += weight * preferences[key]
            similarities[user_type] = similarity
        
        # 归一化相似度
        total = sum(similarities.values())
        if total > 0:
            similarities = {k: v/total for k, v in similarities.items()}
        
        # 确定主要用户类型
        main_type = max(similarities.items(), key=lambda x: x[1])[0]
        
        # 使用DeepSeek对用户类型进行更深入的分析
        prompt = f"请分析以下用户偏好并确定最适合的用户类型。用户类型定义：\n{json.dumps(USER_TYPES, ensure_ascii=False, indent=2)}\n\n用户偏好：{json.dumps(preferences, ensure_ascii=False, indent=2)}\n\n当前系统初步识别的用户类型是：{main_type}（概率分布：{json.dumps(similarities, ensure_ascii=False, indent=2)}）\n\n请返回JSON格式的结果，包含main_type（主要用户类型）、type_probabilities（类型概率分布）和type_characteristics（类型特征）三个字段。如果您认为初步识别不准确，可以调整。"
        
        deepseek_result = call_deepseek_api(prompt, max_tokens=300, temperature=0.3)
        
        if deepseek_result:
            try:
                result = json.loads(deepseek_result)
                return {
                    "main_type": result.get("main_type", main_type),
                    "type_probabilities": result.get("type_probabilities", similarities),
                    "type_characteristics": result.get("type_characteristics", USER_TYPES[main_type])
                }
            except json.JSONDecodeError:
                pass
        
        return {
            "main_type": main_type,
            "type_probabilities": similarities,
            "type_characteristics": USER_TYPES[main_type]
        }
    
    def calculate_preference_weights(self, user_responses: Dict) -> Dict:
        """计算各问题类型的重要性权重"""
        weights = {}
        
        # 基础权重计算
        if "q1" in user_responses:
            response = user_responses["q1"]
            
            # 如果是新的评分字典格式
            if isinstance(response, dict) and response:
                # 将1-5分转换为0-1的权重值
                aspect_weights = {aspect: (score - 1) / 4 for aspect, score in response.items()}
                
                # 根据各服务方面的权重计算具体问题类别的权重
                total_aspect_weight = sum(aspect_weights.values())
                if total_aspect_weight > 0:
                    # 准时性相关权重
                    punctuality_weight = aspect_weights.get("准时性", 0)
                    if punctuality_weight > 0:
                        weights["延误"] = punctuality_weight * 0.4
                        weights["取消"] = punctuality_weight * 0.3
                        weights["信息透明"] = punctuality_weight * 0.3
                    
                    # 舒适性相关权重
                    comfort_weight = aspect_weights.get("舒适性", 0)
                    if comfort_weight > 0:
                        weights["座位"] = comfort_weight * 0.3
                        weights["餐食"] = comfort_weight * 0.3
                        weights["设施"] = comfort_weight * 0.2
                        weights["服务态度"] = weights.get("服务态度", 0) + comfort_weight * 0.2
                    
                    # 经济性相关权重
                    economy_weight = aspect_weights.get("经济性", 0)
                    if economy_weight > 0:
                        weights["补偿"] = economy_weight * 0.4
                        weights["性价比"] = economy_weight * 0.3
                        weights["优惠"] = economy_weight * 0.3
                    
                    # 服务态度相关权重
                    attitude_weight = aspect_weights.get("服务态度", 0)
                    if attitude_weight > 0:
                        weights["服务态度"] = weights.get("服务态度", 0) + attitude_weight * 0.5
                        weights["沟通"] = attitude_weight * 0.3
                        weights["个性化"] = attitude_weight * 0.2
            
            # 兼容旧格式
            else:
                # 如果是单个选择
                if isinstance(response, str) and response:
                    choices = [response]
                # 如果是多个选择
                elif isinstance(response, list) and response:
                    choices = response
                else:
                    choices = []
                
                # 计算基础权重
                for choice in choices:
                    if choice == "准时性":
                        weights["延误"] = weights.get("延误", 0) + 0.4
                        weights["取消"] = weights.get("取消", 0) + 0.3
                        weights["信息透明"] = weights.get("信息透明", 0) + 0.3
                    elif choice == "舒适性":
                        weights["座位"] = weights.get("座位", 0) + 0.3
                        weights["餐食"] = weights.get("餐食", 0) + 0.3
                        weights["设施"] = weights.get("设施", 0) + 0.2
                        weights["服务态度"] = weights.get("服务态度", 0) + 0.2
                    elif choice == "经济性":
                        weights["补偿"] = weights.get("补偿", 0) + 0.4
                        weights["性价比"] = weights.get("性价比", 0) + 0.3
                        weights["优惠"] = weights.get("优惠", 0) + 0.3
                    elif choice == "服务态度":
                        weights["服务态度"] = weights.get("服务态度", 0) + 0.5
                        weights["沟通"] = weights.get("沟通", 0) + 0.3
                        weights["个性化"] = weights.get("个性化", 0) + 0.2
                
                # 如果有多个选择，归一化基础权重
                if len(choices) > 1 and weights:
                    total = sum(weights.values())
                    if total > 0:
                        weights = {k: v/total for k, v in weights.items()}
        
        # 结合评分问题调整权重
        rating_questions = {
            "q2": "延误",
            "eq1": "快速处理",
            "eq2": "信息透明",
            "cq1": "座位",
            "cq2": "餐食",
            "ecq1": "补偿",
            "ecq2": "性价比",
            "emq1": "服务态度",
            "emq2": "个性化"
        }
        
        for q_id, category in rating_questions.items():
            if q_id in user_responses:
                # 将1-5分转换为0-1权重
                weight = (user_responses[q_id] - 1) / 4
                if category in weights:
                    weights[category] = (weights[category] + weight) / 2
                else:
                    weights[category] = weight
        
        # 归一化权重
        total = sum(weights.values())
        if total > 0:
            weights = {k: v/total for k, v in weights.items()}
        
        return weights


class CarePlanGenerator:
    """关怀方案生成器：生成个性化关怀方案"""
    
    def __init__(self):
        self.care_modules = {
            "延误": [
                {"name": "实时通知", "description": "航班延误时每30分钟更新一次信息", "cost": 0.1, "impact": 0.8},
                {"name": "优先改签", "description": "提供免费改签服务", "cost": 0.5, "impact": 0.9},
                {"name": "延误补偿", "description": "根据延误时间提供现金或积分补偿", "cost": 0.7, "impact": 0.95}
            ],
            "取消": [
                {"name": "免费退票", "description": "提供全额退票服务", "cost": 0.3, "impact": 0.8},
                {"name": "酒店安排", "description": "为过夜取消的乘客安排酒店", "cost": 0.8, "impact": 0.9},
                {"name": "升级服务", "description": "为受影响乘客提供舱位升级", "cost": 0.6, "impact": 0.85}
            ],
            "座位": [
                {"name": "优先选座", "description": "提供免费选座服务", "cost": 0.2, "impact": 0.7},
                {"name": "额外空间", "description": "安排额外腿部空间的座位", "cost": 0.5, "impact": 0.85},
                {"name": "舱位升级", "description": "升级到更高等级舱位", "cost": 0.8, "impact": 0.9}
            ],
            "餐食": [
                {"name": "餐食升级", "description": "提供更高级别的餐食选择", "cost": 0.3, "impact": 0.75},
                {"name": "特殊餐食", "description": "根据需求提供特殊餐食", "cost": 0.2, "impact": 0.7},
                {"name": "餐饮券", "description": "提供机场餐饮券", "cost": 0.4, "impact": 0.8}
            ],
            "服务态度": [
                {"name": "专属客服", "description": "提供专属客服经理", "cost": 0.6, "impact": 0.9},
                {"name": "个性化问候", "description": "提供个性化的问候和服务", "cost": 0.1, "impact": 0.7},
                {"name": "道歉信", "description": "提供手写道歉信", "cost": 0.2, "impact": 0.8}
            ],
            "补偿": [
                {"name": "现金补偿", "description": "提供现金形式的补偿", "cost": 0.9, "impact": 0.95},
                {"name": "积分奖励", "description": "提供额外积分奖励", "cost": 0.5, "impact": 0.8},
                {"name": "优惠券", "description": "提供未来航班优惠券", "cost": 0.3, "impact": 0.75}
            ]
        }
    
    def generate_personalized_plan(self, preferences: Dict, user_type: str, customer_value: str = "普通客户") -> Dict:
        """生成个性化关怀方案"""
        plan = {
            "user_type": user_type,
            "customer_value": customer_value,
            "preferences": preferences,
            "care_modules": [],
            "total_cost": 0,
            "total_impact": 0
        }
        
        # 根据客户价值确定关怀力度
        value_multipliers = {
            "普通客户": 0.7,
            "银卡客户": 0.8,
            "金卡客户": 0.9,
            "白金卡客户": 1.0
        }
        multiplier = value_multipliers.get(customer_value, 0.7)
        
        # 为每个优先的问题类型选择合适的关怀模块
        for category, weight in sorted(preferences.items(), key=lambda x: x[1], reverse=True)[:3]:
            if category in self.care_modules:
                modules = self.care_modules[category]
                # 根据权重和客户价值选择模块
                selected_module = None
                if weight > 0.6 and multiplier >= 0.9:
                    selected_module = modules[2]  # 高级方案
                elif weight > 0.4 and multiplier >= 0.8:
                    selected_module = modules[1]  # 中级方案
                else:
                    selected_module = modules[0]  # 基础方案
                
                if selected_module:
                    # 调整成本和影响
                    adjusted_module = selected_module.copy()
                    adjusted_module["adjusted_cost"] = selected_module["cost"] * multiplier
                    adjusted_module["adjusted_impact"] = selected_module["impact"] * weight
                    adjusted_module["category"] = category
                    adjusted_module["weight"] = weight
                    
                    plan["care_modules"].append(adjusted_module)
                    plan["total_cost"] += adjusted_module["adjusted_cost"]
                    plan["total_impact"] += adjusted_module["adjusted_impact"]
        
        # 生成方案描述
        plan["plan_description"] = self._generate_plan_description(plan)
        
        return plan
    
    def _generate_plan_description(self, plan: Dict) -> str:
        """生成方案描述"""
        # 使用DeepSeek生成更自然、专业的方案描述
        modules_text = "\n".join([f"- {module['name']}：{module['description']}（优先级：{module['weight']:.1%}）" for module in plan['care_modules']])
        
        prompt = f"请为一位{plan['user_type']}类型的{plan['customer_value']}生成一份专业、友好的航空公司关怀方案描述。\n\n关怀模块：\n{modules_text}\n\n用户偏好：{json.dumps(plan['preferences'], ensure_ascii=False, indent=2)}\n\n请生成一段流畅的中文描述，包括方案概述、关怀措施和预期效果，不要直接列出模块，要形成连贯的段落。"
        
        deepseek_result = call_deepseek_api(prompt, max_tokens=800, temperature=0.8)
        
        if deepseek_result:
            return deepseek_result
        
        # 兜底方案：如果DeepSeek调用失败，使用传统生成方式
        description = f"针对{plan['user_type']}用户的个性化关怀方案：\n\n"
        
        for module in plan['care_modules']:
            description += f"• {module['name']}：{module['description']}（优先级：{module['weight']:.1%}）\n"
        
        description += f"\n方案总成本指数：{plan['total_cost']:.2f}\n"
        description += f"方案总影响指数：{plan['total_impact']:.2f}\n"
        
        return description


class SmartCareSystem:
    """智能关怀方案生成系统主类"""
    
    def __init__(self):
        self.problem_discovery = ProblemDiscoveryModule()
        self.questionnaire_system = SmartQuestionnaireSystem()
        self.preference_analyzer = UserPreferenceAnalyzer()
        self.care_generator = CarePlanGenerator()
    
    def analyze_tweet_data(self, tweets: List[str]) -> Dict:
        """分析推文数据"""
        # 问题发现分析
        problem_analysis = self.problem_discovery.analyze_tweets(tweets)
        
        # 问题分类
        classified_tweets = [self.problem_discovery.classify_problem(tweet) for tweet in tweets]
        df_classified = pd.DataFrame(classified_tweets)
        
        # 问题关联分析
        associations = self.problem_discovery.analyze_problem_associations(tweets)
        
        return {
            "problem_analysis": problem_analysis,
            "category_distribution": df_classified.groupby(['primary_category', 'secondary_category']).size().reset_index(name='count').to_dict('records'),
            "problem_associations": associations
        }
    
    def generate_questionnaire(self, user_responses: Optional[Dict] = None) -> List[Dict]:
        """生成问卷"""
        if not user_responses:
            return self.questionnaire_system.generate_initial_questionnaire()
        else:
            initial_questions = self.questionnaire_system.generate_initial_questionnaire()
            adaptive_questions = self.questionnaire_system.generate_adaptive_questions(user_responses)
            return initial_questions + adaptive_questions
    
    def analyze_preferences(self, user_responses: Dict) -> Dict:
        """分析用户偏好"""
        # 计算偏好权重
        weights = self.preference_analyzer.calculate_preference_weights(user_responses)
        
        # 识别用户类型
        user_type = self.preference_analyzer.identify_user_type(weights)
        
        return {
            "preference_weights": weights,
            "user_type": user_type
        }
    
    def generate_care_plan(self, preferences: Dict, user_type: str, customer_value: str = "普通客户") -> Dict:
        """生成关怀方案"""
        return self.care_generator.generate_personalized_plan(preferences, user_type, customer_value)
    
    async def generate_full_care_plan(self, tweets: List[str], user_responses: Dict, customer_value: str = "普通客户") -> Dict:
        """生成完整的关怀方案"""
        # 分析推文数据
        tweet_analysis = self.analyze_tweet_data(tweets)
        
        # 分析用户偏好
        preference_analysis = self.analyze_preferences(user_responses)
        
        # 生成关怀方案
        care_plan = self.generate_care_plan(
            preference_analysis["preference_weights"],
            preference_analysis["user_type"]["main_type"],
            customer_value
        )
        
        return {
            "tweet_analysis": tweet_analysis,
            "preference_analysis": preference_analysis,
            "care_plan": care_plan
        }
