"""智能客服优化系统 - 基于意图识别和实时NLP"""

import os
import asyncio
from dotenv import load_dotenv
import pandas as pd
import numpy as np
from typing import List, Dict, Tuple, Optional
from pydantic import BaseModel, Field
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import re
from datetime import datetime
from collections import defaultdict
from pydantic_ai import Agent

# 加载环境变量
load_dotenv()


class IntentAnalysis(BaseModel):
    """意图分析结果"""
    主要意图: str = Field(description="主要意图分类")
    紧急程度: str = Field(description="紧急程度(高/中/低)")
    问题类型: str = Field(description="问题类型分类")
    情感强度: float = Field(description="情感强度得分")
    关键词: List[str] = Field(description="关键识别词")
    置信度: float = Field(description="分析置信度")
    是否为易流失客户: str = Field(description="是否为易流失客户群体(高/中/低风险)")
    流失风险评分: float = Field(description="流失风险评分(0-100)")
    流失风险原因: List[str] = Field(description="流失风险原因分析")


class RoutingDecision(BaseModel):
    """路由决策结果"""
    处理方式: str = Field(description="处理方式(自动回复/人工介入/升级处理)")
    优先级: str = Field(description="处理优先级")
    预计响应时间: str = Field(description="预计响应时间")
    推荐部门: str = Field(description="推荐处理部门")
    路由理由: str = Field(description="路由决策理由")


class ResponseSuggestion(BaseModel):
    """回复建议"""
    开场白: str = Field(description="对话开场白")
    核心回复: str = Field(description="核心问题回复")
    安抚语句: str = Field(description="安抚客户语句")
    解决方案: List[str] = Field(description="具体解决方案")
    结束语: str = Field(description="对话结束语")
    个性化建议: str = Field(description="个性化建议")


class ConversationPattern(BaseModel):
    """对话模式"""
    模式类型: str = Field(description="模式类型")
    成功案例: List[str] = Field(description="成功案例")
    关键话术: List[str] = Field(description="关键话术")
    适用场景: List[str] = Field(description="适用场景")
    效果评估: float = Field(description="效果评估得分")


class SmartCustomerService:
    """智能客服优化系统"""
    
    def __init__(self, data_path: str = "data/Tweets.csv"):
        self.data_path = data_path
        self.vectorizer = TfidfVectorizer(max_features=1000, stop_words='english')
        self.intent_classifier = None
        self.routing_model = None
        self.conversation_patterns = {}
        self.success_cases = self._load_success_cases()
        
        # 意图分类标签
        self.intent_categories = [
            "投诉", "咨询", "建议", "表扬", "紧急求助", "一般问题"
        ]
        
        # 问题类型分类
        self.problem_types = [
            "航班延误", "行李问题", "服务态度", "座位问题", "餐饮质量",
            "登机流程", "取消航班", "超售问题", "预订问题", "其他"
        ]
        
        # 路由决策规则
        self.routing_rules = {
            "紧急求助": {"处理方式": "升级处理", "优先级": "最高", "响应时间": "立即"},
            "投诉": {"处理方式": "人工介入", "优先级": "高", "响应时间": "30分钟内"},
            "咨询": {"处理方式": "自动回复", "优先级": "中", "响应时间": "1小时内"},
            "建议": {"处理方式": "自动回复", "优先级": "低", "响应时间": "24小时内"},
            "表扬": {"处理方式": "自动回复", "优先级": "低", "响应时间": "24小时内"}
        }
    
    def _load_success_cases(self) -> List[Dict]:
        """加载成功案例数据"""
        # 模拟成功案例数据
        return [
            {
                "text": "航班延误了3小时，很失望",
                "response": "非常抱歉给您带来不便。我们已为您安排优先登机和里程补偿。",
                "satisfaction": 0.8,
                "pattern": "延误安抚+补偿"
            },
            {
                "text": "行李被损坏了，怎么办？",
                "response": "很遗憾听到这个消息。请立即联系行李服务台，我们将为您处理赔偿。",
                "satisfaction": 0.9,
                "pattern": "问题解决+赔偿"
            }
        ]
    
    def train_intent_classifier(self) -> None:
        """训练意图识别分类器"""
        # 创建更丰富的训练数据（支持中英文）
        training_data = [
            # 投诉类 - 更多样本
            ("航班延误了3小时，没有任何解释", "投诉"),
            ("我的行李被损坏了，非常生气", "投诉"),
            ("客服态度很差，很不满意", "投诉"),
            ("服务太差了，再也不坐了", "投诉"),
            ("飞机晚点4小时，没有任何补偿", "投诉"),
            ("座位不舒服，飞行体验很糟糕", "投诉"),
            ("餐饮质量很差，难以下咽", "投诉"),
            ("delay flight 3 hours no explanation", "投诉"),
            ("my luggage damaged very angry", "投诉"),
            
            # 紧急求助类 - 更多样本
            ("紧急求助，航班取消了怎么办", "紧急求助"),
            ("救命，行李丢失了", "紧急求助"),
            ("紧急情况，护照丢失了", "紧急求助"),
            ("urgent help flight cancelled what to do", "紧急求助"),
            ("help lost luggage emergency", "紧急求助"),
            
            # 咨询类 - 更多样本
            ("请问航班什么时候起飞", "咨询"),
            ("行李托运有什么规定", "咨询"),
            ("如何办理登机手续", "咨询"),
            ("航班改签需要什么手续", "咨询"),
            ("what time does the flight depart", "咨询"),
            ("baggage allowance rules", "咨询"),
            
            # 建议类
            ("建议改进登机流程", "建议"),
            ("希望增加航班频次", "建议"),
            ("suggest improve boarding process", "建议"),
            ("hope increase flight frequency", "建议"),
            
            # 表扬类
            ("服务很好，非常满意", "表扬"),
            ("空乘人员态度很好", "表扬"),
            ("service excellent very satisfied", "表扬"),
            ("flight attendant very friendly", "表扬"),
        ]
        
        texts = [data[0] for data in training_data]
        intent_labels = [data[1] for data in training_data]
        
        print(f"训练数据数量: {len(texts)}")
        print(f"意图类别分布: {dict(zip(*np.unique(intent_labels, return_counts=True)))}")
        
        # 特征提取
        X = self.vectorizer.fit_transform(texts)
        print(f"特征维度: {X.shape}")
        
        # 训练分类器
        self.intent_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
        self.intent_classifier.fit(X, intent_labels)
        
        # 打印分类器信息
        print(f"分类器类别: {self.intent_classifier.classes_}")
        print("分类器训练完成！")
    
    async def analyze_intent_deepseek(self, text: str) -> IntentAnalysis:
        """深度意图分析 - 完全基于DeepSeek思考"""
        # 使用DeepSeek进行深度意图分析
        deep_analysis = await analyze_deep_intent(text)
        
        # 提取DeepIntentAnalysis对象
        if hasattr(deep_analysis, 'data'):
            deep_analysis = deep_analysis.data
        elif hasattr(deep_analysis, 'result'):
            deep_analysis = deep_analysis.result
        elif hasattr(deep_analysis, 'output'):
            deep_analysis = deep_analysis.output
        elif hasattr(deep_analysis, 'value'):
            deep_analysis = deep_analysis.value
        
        # 转换为IntentAnalysis对象
        return IntentAnalysis(
            主要意图=deep_analysis.主要意图,
            紧急程度=deep_analysis.紧急程度,
            问题类型=deep_analysis.问题类型,
            情感强度=deep_analysis.情感强度,
            关键词=deep_analysis.关键词,
            置信度=deep_analysis.置信度,
            是否为易流失客户=deep_analysis.是否为易流失客户,
            流失风险评分=deep_analysis.流失风险评分,
            流失风险原因=deep_analysis.流失风险原因
        )

    def analyze_intent(self, text: str) -> IntentAnalysis:
        """分析用户意图（基于关键词的可靠方法）"""
        text_lower = text.lower()
        
        # 基于关键词的意图识别（更可靠的方法）
        intent_keywords = {
            "投诉": [
                # 航班延误相关
                "延误", "晚点", "延迟", "误点", "推迟", "取消", "改签", "航班取消", "航班延误",
                "起飞晚点", "到达晚点", "长时间延误", "延误赔偿", "延误补偿",
                
                # 服务态度相关
                "态度差", "服务差", "态度恶劣", "服务态度", "客服态度", "空乘态度", "不耐烦",
                "冷漠", "不专业", "不负责任", "推诿", "扯皮", "敷衍", "应付", "白眼", "白了一眼",
                "白了我一眼", "翻白眼", "瞪眼", "瞪了一眼", "瞪了我一眼", "不耐烦", "爱理不理", 
                "不理不睬", "冷眼相待", "态度冷淡", "态度傲慢", "态度恶劣", "态度蛮横", "态度粗暴",
                "服务不周", "服务不到位", "服务态度差", "服务态度恶劣", "服务态度不好",
                "空乘态度差", "空乘态度恶劣", "空乘服务差", "空乘不耐烦", "空乘冷漠",
                "空乘不专业", "空乘不负责任", "空乘推诿", "空乘敷衍", "空乘应付",
                "空乘白眼", "空乘翻白眼", "空乘瞪眼", "空乘爱理不理", "空乘不理不睬",
                "空乘冷眼相待", "空乘态度冷淡", "空乘态度傲慢", "空乘态度蛮横",
                "空乘态度粗暴", "空乘服务不周", "空乘服务不到位", "空乘服务态度差",
                "空乘服务态度恶劣", "空乘服务态度不好", "乘务员态度差", "乘务员态度恶劣",
                "乘务员服务差", "乘务员不耐烦", "乘务员冷漠", "乘务员不专业",
                "乘务员不负责任", "乘务员推诿", "乘务员敷衍", "乘务员应付",
                "乘务员白眼", "乘务员翻白眼", "乘务员瞪眼", "乘务员爱理不理",
                "乘务员不理不睬", "乘务员冷眼相待", "乘务员态度冷淡", "乘务员态度傲慢",
                "乘务员态度蛮横", "乘务员态度粗暴", "乘务员服务不周", "乘务员服务不到位",
                "乘务员服务态度差", "乘务员服务态度恶劣", "乘务员服务态度不好",
                "rude", "impolite", "unfriendly", "bad attitude", "poor service", "unprofessional",
                "disrespectful", "ignored", "snubbed", "looked down upon", "treated badly",
                
                # 餐饮质量相关
                "太难吃", "难吃", "不好吃", "味道差", "餐饮质量", "飞机餐", "餐食", "饮料",
                "食物", "饭菜", "难以下咽", "吃不下去", "口味差", "质量差", "不新鲜",
                
                # 行李问题相关
                "行李损坏", "行李丢失", "行李延误", "托运问题", "行李破损", "行李超重",
                "行李超规", "行李赔偿", "行李找不到", "行李被撬", "行李被开",
                
                # 座位舒适度相关
                "座位不舒服", "座位窄", "空间小", "腿部空间", "座椅", "靠背", "座位间距",
                "拥挤", "不舒服", "难受", "坐得不舒服", "座位问题",
                
                # 登机流程相关
                "登机慢", "排队时间长", "安检慢", "值机慢", "登机流程", "候机时间长",
                "登机口变更", "登机混乱", "秩序差", "管理混乱",
                
                # 整体体验相关
                "体验差", "体验糟糕", "很差", "太差", "糟糕透顶", "失望", "不满意", "生气",
                "愤怒", "恼火", "无语", "崩溃", "绝望", "后悔", "再也不坐", "换航空公司",
                "投诉到底", "非常失望", "极度不满", "糟糕体验", "差评", "差劲",
                
                # 英文关键词
                "delay", "cancel", "damage", "lost", "angry", "terrible", "awful", "disgusting",
                "bad service", "poor experience", "terrible food", "uncomfortable", "crowded",
                "slow boarding", "long queue", "bad attitude", "rude staff", "horrible"
            ],
            "紧急求助": [
                "紧急", "求助", "救命", "怎么办", "急事", "突发事件", "紧急情况", "急需帮助",
                "urgent", "help", "emergency", "what to do", "need help", "urgent help"
            ],
            "咨询": [
                "请问", "什么", "如何", "多少", "什么时候", "哪里", "能否", "是否可以",
                "when", "what", "how", "where", "which", "can", "could", "would"
            ],
            "建议": [
                "建议", "希望", "改进", "建议改进", "提个建议", "希望改进", "建议增加",
                "suggest", "hope", "improve", "recommend", "advice"
            ],
            "表扬": [
                "很好", "满意", "优秀", "感谢", "很棒", "非常好", "很满意", "服务很好",
                "态度很好", "体验很好", "值得表扬", "点赞", "好评", "推荐", "下次还坐",
                "great", "excellent", "satisfied", "thank", "wonderful", "fantastic", "amazing"
            ]
        }
        
        # 计算每个意图的匹配分数
        intent_scores = {}
        for intent, keywords in intent_keywords.items():
            score = 0
            for keyword in keywords:
                # 使用更灵活的匹配方式：包含匹配和中文分词匹配
                # 中文文本需要特殊处理，因为split()对中文分词效果不好
                if keyword in text_lower:
                    score += 1
            intent_scores[intent] = score
        
        # 情感强度分析（先执行，因为后面需要用到）
        sentiment_intensity = self._analyze_sentiment_intensity(text)
        
        # 选择得分最高的意图（考虑意图优先级）
        max_score = max(intent_scores.values())
        if max_score > 0:
            # 找到得分最高的意图
            best_intents = [intent for intent, score in intent_scores.items() if score == max_score]
            
            # 如果有多个意图得分相同，按优先级选择
            intent_priority = ["紧急求助", "投诉", "咨询", "建议", "表扬"]
            
            # 按优先级排序最佳意图
            best_intents_sorted = sorted(best_intents, 
                                       key=lambda x: intent_priority.index(x) if x in intent_priority else len(intent_priority))
            
            intent = best_intents_sorted[0]  # 选择优先级最高的意图
            confidence = min(0.99, max_score / len(intent_keywords[intent]))
        else:
            # 没有匹配到关键词，根据情感强度判断意图
            if sentiment_intensity < -0.3:
                intent = "投诉"  # 负面情感默认为投诉
                confidence = 0.6
            else:
                intent = "咨询"
                confidence = 0.3
        
        # 关键词提取
        keywords = self._extract_keywords(text)
        
        # 问题类型分类
        problem_type = self._classify_problem_type(text)
        
        # 紧急程度评估
        urgency_level = self._assess_urgency(text, intent, sentiment_intensity)
        
        # 流失客户群体分析
        churn_risk_result = self._analyze_churn_risk(text, intent, sentiment_intensity, urgency_level)
        
        # 调试信息
        print(f"=== 意图分析结果 ===")
        print(f"输入文本: {text}")
        print(f"意图得分: {intent_scores}")
        print(f"最终意图: {intent}")
        print(f"置信度: {confidence:.2f}")
        print(f"情感强度: {sentiment_intensity:.2f}")
        print(f"流失风险: {churn_risk_result['风险等级']} (评分: {churn_risk_result['风险评分']})")
        print(f"风险原因: {churn_risk_result['风险原因']}")
        
        return IntentAnalysis(
            主要意图=intent,
            紧急程度=urgency_level,
            问题类型=problem_type,
            情感强度=sentiment_intensity,
            关键词=keywords,
            置信度=confidence,
            是否为易流失客户=churn_risk_result['风险等级'],
            流失风险评分=churn_risk_result['风险评分'],
            流失风险原因=churn_risk_result['风险原因']
        )
    
    def make_routing_decision(self, intent_analysis: IntentAnalysis) -> RoutingDecision:
        """制定路由决策"""
        # 基于意图和紧急程度制定路由决策
        base_decision = self.routing_rules.get(intent_analysis.主要意图, {
            "处理方式": "人工介入", "优先级": "中", "响应时间": "2小时内"
        })
        
        # 根据紧急程度调整决策
        if intent_analysis.紧急程度 == "高":
            base_decision["处理方式"] = "升级处理"
            base_decision["优先级"] = "最高"
            base_decision["响应时间"] = "立即"
        elif intent_analysis.紧急程度 == "中":
            if base_decision["处理方式"] == "自动回复":
                base_decision["处理方式"] = "人工介入"
        
        # 推荐处理部门
        department = self._recommend_department(intent_analysis.问题类型)
        
        # 路由理由
        routing_reason = self._generate_routing_reason(intent_analysis, base_decision)
        
        return RoutingDecision(
            处理方式=base_decision["处理方式"],
            优先级=base_decision["优先级"],
            预计响应时间=base_decision["响应时间"],
            推荐部门=department,
            路由理由=routing_reason
        )
    
    def generate_response_suggestions(self, text: str, intent_analysis: IntentAnalysis, 
                                    routing_decision: RoutingDecision) -> ResponseSuggestion:
        """生成回复建议"""
        # 基于意图和问题类型生成回复
        opening = self._generate_opening(intent_analysis)
        core_response = self._generate_core_response(text, intent_analysis)
        comforting_phrase = self._generate_comforting_phrase(intent_analysis)
        solutions = self._generate_solutions(intent_analysis)
        closing = self._generate_closing(intent_analysis)
        personalization = self._generate_personalization(intent_analysis)
        
        return ResponseSuggestion(
            开场白=opening,
            核心回复=core_response,
            安抚语句=comforting_phrase,
            解决方案=solutions,
            结束语=closing,
            个性化建议=personalization
        )
    
    def learn_conversation_patterns(self) -> Dict[str, ConversationPattern]:
        """学习对话模式"""
        patterns = {}
        
        # 分析成功案例，提取模式
        for case in self.success_cases:
            pattern_type = case["pattern"]
            
            if pattern_type not in patterns:
                patterns[pattern_type] = ConversationPattern(
                    模式类型=pattern_type,
                    成功案例=[case["response"]],
                    关键话术=self._extract_key_phrases(case["response"]),
                    适用场景=[case["text"]],
                    效果评估=case["satisfaction"]
                )
            else:
                patterns[pattern_type].成功案例.append(case["response"])
                patterns[pattern_type].适用场景.append(case["text"])
        
        return patterns
    
    def _preprocess_text(self, text: str) -> str:
        """文本预处理（支持中英文）"""
        if pd.isna(text):
            return ""
        
        text = str(text).lower()
        # 只移除英文标点，保留中文字符
        text = re.sub(r'[^\w\s\u4e00-\u9fff]', '', text)
        text = re.sub(r'\s+', ' ', text)  # 移除多余空格
        
        return text.strip()
    
    def _extract_keywords(self, text: str) -> List[str]:
        """提取关键词（支持中英文）"""
        keywords = []
        
        # 问题相关关键词（中英文）
        problem_keywords = [
            'delay', 'cancel', 'baggage', 'service', 'seat', 'food',
            '延误', '取消', '行李', '服务', '座位', '餐饮', '客服', '态度'
        ]
        for keyword in problem_keywords:
            if keyword in text.lower():
                keywords.append(keyword)
        
        # 情感相关关键词（中英文）
        sentiment_keywords = [
            'terrible', 'awful', 'disappointing', 'great', 'excellent',
            '生气', '失望', '满意', '很好', '优秀'
        ]
        for keyword in sentiment_keywords:
            if keyword in text.lower():
                keywords.append(keyword)
        
        return keywords[:5]  # 返回前5个关键词
    
    def _analyze_sentiment_intensity(self, text: str) -> float:
        """分析情感强度（支持中英文）"""
        text_lower = text.lower()
        
        # 强烈负面情感词（中英文）
        strong_negative = ['terrible', 'awful', 'horrible', 'disgusting', 'hate',
                          '非常生气', '极度不满', '糟糕透顶', '恶心', '恨', '愤怒']
        # 一般负面情感词
        negative = ['bad', 'poor', 'disappointing', 'frustrated',
                   '不满意', '失望', '生气', '糟糕', '差劲']
        # 正面情感词
        positive = ['great', 'excellent', 'wonderful', 'satisfied',
                   '很好', '优秀', '满意', '不错', '喜欢']
        
        intensity = 0.0
        
        # 检查强烈负面词
        for word in strong_negative:
            if word in text_lower:
                intensity -= 0.8
                break  # 找到强烈负面词就停止
        
        # 检查一般负面词
        for word in negative:
            if word in text_lower:
                intensity -= 0.4
                break
        
        # 检查正面词
        for word in positive:
            if word in text_lower:
                intensity += 0.6
                break
        
        # 考虑感叹号和重复字符（中文和英文）
        exclamation_count = text.count('!') + text.count('！')
        if exclamation_count > 0:
            intensity -= min(0.3, exclamation_count * 0.1)
        
        # 考虑负面程度副词
        negative_modifiers = ['非常', '特别', '极其', '十分', '太']
        for modifier in negative_modifiers:
            if modifier in text:
                intensity -= 0.2
                break
        
        # 考虑正面程度副词
        positive_modifiers = ['非常', '特别', '极其', '十分', '很']
        for modifier in positive_modifiers:
            if modifier in text and intensity > 0:
                intensity += 0.2
                break
        
        # 如果没有检测到情感词，根据内容判断
        if intensity == 0.0:
            # 检查是否包含问题描述
            problem_words = ['延误', '取消', '损坏', '丢失', '态度差', '问题']
            if any(word in text for word in problem_words):
                intensity = -0.3  # 默认轻微负面
            else:
                intensity = 0.1   # 中性或轻微正面
        
        return max(-1.0, min(1.0, intensity))
    
    def _classify_problem_type(self, text: str) -> str:
        """分类问题类型（支持中英文，支持复合问题识别）"""
        text_lower = text.lower()
        
        # 扩展问题类型映射，包含更多关键词
        problem_mapping = {
            "航班延误": ['delay', 'late', 'waiting', '延误', '晚点', '延迟', '误点', '推迟', '取消', '改签'],
            "行李问题": ['baggage', 'luggage', 'suitcase', '行李', '托运', '箱子', '损坏', '丢失', '延误'],
            "服务态度": ['service', 'attitude', 'rude', '服务', '态度', '客服', '空乘', '乘务员', 
                        '白眼', '翻白眼', '瞪眼', '不耐烦', '冷漠', '不专业', '不负责任', '敷衍', '应付'],
            "座位问题": ['seat', 'comfortable', 'space', '座位', '舒适', '空间', '窄', '拥挤', '不舒服', '臭', '异味'],
            "餐饮质量": ['food', 'meal', 'drink', '餐饮', '食物', '饮料', '难吃', '味道差', '质量差', '不新鲜']
        }
        
        # 检测所有匹配的问题类型
        detected_problems = []
        for problem_type, keywords in problem_mapping.items():
            if any(keyword in text_lower for keyword in keywords):
                detected_problems.append(problem_type)
        
        # 根据匹配数量返回结果
        if len(detected_problems) == 0:
            return "其他"
        elif len(detected_problems) == 1:
            return detected_problems[0]
        else:
            # 返回复合问题描述
            return "复合问题：" + "、".join(detected_problems)
    
    def _assess_urgency(self, text: str, intent: str, sentiment: float) -> str:
        """评估紧急程度"""
        # 基于意图和情感强度评估紧急程度
        if intent == "紧急求助":
            return "高"
        elif sentiment < -0.5:
            return "高"
        elif sentiment < -0.2:
            return "中"
        else:
            return "低"
    
    def _analyze_churn_risk(self, text: str, intent: str, sentiment: float, urgency: str) -> Dict:
        """分析流失客户风险"""
        text_lower = text.lower()
        
        # 流失风险评分（0-100分）
        risk_score = 0
        risk_reasons = []
        
        # 1. 情感强度因素（权重40%）
        if sentiment < -0.7:
            risk_score += 40
            risk_reasons.append("情感强度极高（强烈不满）")
        elif sentiment < -0.3:
            risk_score += 25
            risk_reasons.append("情感强度较高（明显不满）")
        elif sentiment < 0:
            risk_score += 10
            risk_reasons.append("情感强度偏低（轻微不满）")
        
        # 2. 意图类型因素（权重30%）
        if intent == "投诉":
            risk_score += 30
            risk_reasons.append("客户提出正式投诉")
        elif intent == "紧急求助":
            risk_score += 20
            risk_reasons.append("客户需要紧急帮助")
        elif intent == "建议":
            risk_score += 5
            risk_reasons.append("客户提出改进建议")
        
        # 3. 紧急程度因素（权重20%）
        if urgency == "高":
            risk_score += 20
            risk_reasons.append("问题紧急程度高")
        elif urgency == "中":
            risk_score += 10
            risk_reasons.append("问题紧急程度中等")
        
        # 4. 关键词因素（权重10%）
        churn_keywords = [
            "再也不坐", "取消会员", "换航空公司", "投诉到底", "非常失望",
            "never again", "cancel membership", "switch airline", "file complaint"
        ]
        for keyword in churn_keywords:
            if keyword in text_lower:
                risk_score += 10
                risk_reasons.append(f"包含流失关键词：{keyword}")
                break
        
        # 5. 问题重复性因素（额外加分）
        problem_count = len([word for word in ['延误', '取消', '损坏', '丢失', '态度差'] 
                           if word in text])
        if problem_count > 1:
            risk_score += min(15, problem_count * 5)
            risk_reasons.append(f"涉及多个问题点（{problem_count}个）")
        
        # 确定风险等级
        if risk_score >= 70:
            risk_level = "高风险"
        elif risk_score >= 40:
            risk_level = "中风险"
        else:
            risk_level = "低风险"
        
        # 如果没有检测到风险因素，添加默认说明
        if not risk_reasons:
            risk_reasons.append("客户情绪稳定，无明显流失风险")
        
        return {
            "风险等级": risk_level,
            "风险评分": min(100, risk_score),
            "风险原因": risk_reasons
        }
    
    def _recommend_department(self, problem_type: str) -> str:
        """推荐处理部门"""
        department_mapping = {
            "航班延误": "运营部门",
            "行李问题": "行李服务部",
            "服务态度": "客户服务部",
            "座位问题": "客舱服务部",
            "餐饮质量": "餐饮服务部",
            "其他": "综合服务部"
        }
        
        return department_mapping.get(problem_type, "综合服务部")
    
    def _generate_routing_reason(self, intent_analysis: IntentAnalysis, decision: Dict) -> str:
        """生成路由理由"""
        reasons = []
        
        if intent_analysis.紧急程度 == "高":
            reasons.append("问题紧急程度高")
        
        if intent_analysis.主要意图 == "投诉":
            reasons.append("客户投诉需要专业处理")
        
        if intent_analysis.情感强度 < -0.5:
            reasons.append("客户情感强烈，需要安抚")
        
        return "; ".join(reasons) if reasons else "标准处理流程"
    
    def _generate_opening(self, intent_analysis: IntentAnalysis) -> str:
        """生成开场白"""
        openings = {
            "投诉": "非常抱歉给您带来不便",
            "紧急求助": "我们立即为您处理",
            "咨询": "感谢您的咨询",
            "建议": "感谢您的宝贵建议",
            "表扬": "感谢您的认可和鼓励"
        }
        
        return openings.get(intent_analysis.主要意图, "感谢您联系我们")
    
    def _generate_core_response(self, text: str, intent_analysis: IntentAnalysis) -> str:
        """生成核心回复"""
        # 基于问题类型生成针对性回复
        responses = {
            "航班延误": "我们正在密切关注航班状态，将及时为您提供最新信息",
            "行李问题": "我们已记录您的行李问题，将安排专人跟进处理",
            "服务态度": "我们非常重视服务品质，将加强相关人员培训",
            "座位问题": "我们将优化座位分配流程，提升乘坐舒适度"
        }
        
        return responses.get(intent_analysis.问题类型, "我们已收到您的反馈，将尽快处理")
    
    def _generate_comforting_phrase(self, intent_analysis: IntentAnalysis) -> str:
        """生成安抚语句"""
        if intent_analysis.情感强度 < -0.3:
            return "我们理解您的心情，将尽力解决您的问题"
        else:
            return "感谢您的耐心和理解"
    
    def _generate_solutions(self, intent_analysis: IntentAnalysis) -> List[str]:
        """生成解决方案"""
        solutions_map = {
            "航班延误": ["提供实时航班信息", "安排优先登机", "提供餐饮补偿"],
            "行李问题": ["启动行李追踪", "安排赔偿流程", "提供临时用品"],
            "服务态度": ["安排专人回访", "提供服务改进", "给予适当补偿"]
        }
        
        return solutions_map.get(intent_analysis.问题类型, ["记录问题并跟进", "提供解决方案"])
    
    def _generate_closing(self, intent_analysis: IntentAnalysis) -> str:
        """生成结束语"""
        if intent_analysis.主要意图 == "投诉":
            return "再次为给您带来的不便表示歉意，我们将持续改进服务"
        else:
            return "感谢您选择我们，期待再次为您服务"
    
    def _generate_personalization(self, intent_analysis: IntentAnalysis) -> str:
        """生成个性化建议"""
        if intent_analysis.情感强度 < -0.5:
            return "建议客服人员使用更温和的语气，重点安抚客户情绪"
        elif intent_analysis.紧急程度 == "高":
            return "建议立即响应，避免问题升级"
        else:
            return "标准处理流程，保持专业服务态度"
    
    def _extract_key_phrases(self, text: str) -> List[str]:
        """提取关键话术"""
        # 简单提取重要短语
        phrases = []
        
        important_words = ['抱歉', '感谢', '立即', '解决', '补偿', '改进']
        for word in important_words:
            if word in text:
                # 提取包含关键词的短语
                start = max(0, text.find(word) - 10)
                end = min(len(text), text.find(word) + 20)
                phrases.append(text[start:end].strip())
        
        return phrases[:3]  # 返回前3个关键话术
    
    def load_data(self) -> pd.DataFrame:
        """加载数据"""
        df = pd.read_csv(self.data_path)
        return df


# 创建深度意图分析Agent
class DeepIntentAnalysis(BaseModel):
    """深度意图分析结果"""
    主要意图: str = Field(description="主要意图分类")
    紧急程度: str = Field(description="紧急程度(高/中/低)")
    问题类型: str = Field(description="问题类型分类")
    情感强度: float = Field(description="情感强度得分")
    关键词: List[str] = Field(description="关键识别词")
    置信度: float = Field(description="分析置信度")
    是否为易流失客户: str = Field(description="是否为易流失客户群体(高/中/低风险)")
    流失风险评分: float = Field(description="流失风险评分(0-100)")
    流失风险原因: List[str] = Field(description="流失风险原因分析")
    深度分析说明: str = Field(description="深度分析说明和推理过程")

# 创建智能客服Agent
class SmartServiceAnalysis(BaseModel):
    """智能服务分析结果"""
    意图深度分析: str = Field(description="意图深度分析")
    最佳处理策略: str = Field(description="最佳处理策略")
    话术优化建议: str = Field(description="话术优化建议")
    预期效果: str = Field(description="预期效果评估")
    改进机会: str = Field(description="服务改进机会")

# 创建深度意图分析Agent
deep_intent_agent = Agent(
    'deepseek:deepseek-chat',
    system_prompt="""
    你是专业的客户意图分析专家，专门分析航空服务领域的客户反馈。
    
    你的任务是基于客户反馈进行深度意图分析，包括：
    1. 准确识别客户的主要意图和真实需求
    2. 评估问题的紧急程度和情感强度
    3. 分析客户流失风险和潜在问题
    4. 提供深度分析和推理过程
    
    分析要点：
    - 理解客户的情感表达和隐含需求
    - 考虑航空服务的特殊性（航班延误、服务态度、座位舒适度等）
    - 基于上下文进行综合判断
    - 提供详细的分析说明和推理过程
    
    输出必须是结构化的JSON格式。
    """,
    output_type=DeepIntentAnalysis
)


smart_service_agent = Agent(
    'deepseek:deepseek-chat',
    system_prompt="""
    你是智能客服专家，基于NLP和机器学习技术优化客户服务流程。
    
    你的任务：
    1. 深度分析客户意图和情感状态
    2. 制定最优处理策略和话术
    3. 预测服务效果和改进机会
    4. 提供基于数据的最佳实践建议
    
    分析要点：
    - 关注客户真实需求和情感表达
    - 考虑服务效率和客户满意度平衡
    - 基于历史成功案例优化策略
    - 提供可操作的具体建议
    
    输出必须是结构化的JSON格式。
    """,
    output_type=SmartServiceAnalysis
)


async def analyze_deep_intent(customer_text: str) -> DeepIntentAnalysis:
    """深度意图分析 - 完全基于DeepSeek思考"""
    result = await deep_intent_agent.run(f"""
    请对以下航空服务客户反馈进行深度意图分析：
    
    客户反馈: "{customer_text}"
    
    请进行深度分析：
    1. 主要意图识别：投诉、咨询、建议、表扬、紧急求助
    2. 紧急程度评估：高、中、低
    3. 问题类型分类：航班延误、服务态度、座位问题、餐饮质量、行李问题等
    4. 情感强度分析：-1.0（极度负面）到1.0（极度正面）
    5. 关键词提取：从客户反馈中提取关键识别词
    6. 流失风险评估：分析客户流失风险和原因
    7. 深度分析说明：详细说明分析过程和推理
    
    请基于深度思考，不要简单依赖关键词匹配。
    """)
    
    return result


# 创建回复话术生成Agent
class CustomerReply(BaseModel):
    """客户回复话术"""
    开场白: str = Field(description="开场白和问候语")
    问题确认: str = Field(description="问题确认和共情表达")
    解决方案: str = Field(description="具体解决方案和措施")
    补偿措施: str = Field(description="补偿或安抚措施")
    结束语: str = Field(description="结束语和后续跟进")
    个性化调整: str = Field(description="个性化调整建议")


reply_agent = Agent(
    'deepseek:deepseek-chat',
    system_prompt="""
    你是专业的客服话术专家，专门为航空服务设计直接可用的客户回复话术。
    
    你的任务是基于智能分析结果，生成可以直接复制粘贴使用的客户回复话术：
    1. 开场白和问候语 - 专业友好的开场
    2. 问题确认和共情 - 理解客户感受
    3. 具体解决方案 - 明确可行的解决措施
    4. 补偿措施 - 适当的补偿或安抚
    5. 结束语 - 专业的结束和后续安排
    6. 个性化调整 - 根据具体情况微调
    
    话术要求：
    - 专业、友好、共情
    - 具体、可行、可操作
    - 符合航空服务行业标准
    - 可以直接复制使用
    
    输出必须是结构化的JSON格式。
    """,
    output_type=CustomerReply
)


async def generate_customer_reply(customer_text: str, intent_analysis: IntentAnalysis, 
                                 smart_analysis: SmartServiceAnalysis) -> CustomerReply:
    """生成直接可用的客户回复话术"""
    result = await reply_agent.run(f"""
    请基于以下智能分析结果，生成可以直接复制使用的客户回复话术：
    
    客户反馈: "{customer_text}"
    
    意图分析结果:
    - 主要意图: {intent_analysis.主要意图}
    - 紧急程度: {intent_analysis.紧急程度}
    - 问题类型: {intent_analysis.问题类型}
    - 情感强度: {intent_analysis.情感强度:.2f}
    - 流失风险: {intent_analysis.是否为易流失客户}
    
    深度智能分析:
    - 意图深度分析: {smart_analysis.意图深度分析}
    - 最佳处理策略: {smart_analysis.最佳处理策略}
    - 话术优化建议: {smart_analysis.话术优化建议}
    - 预期效果: {smart_analysis.预期效果}
    
    请生成可以直接复制粘贴使用的完整回复话术。
    """)
    
    return result


async def analyze_smart_service_strategy(customer_text: str, intent_analysis: IntentAnalysis) -> SmartServiceAnalysis:
    """分析智能服务策略"""
    result = await smart_service_agent.run(f"""
    请基于以下客户反馈和意图分析，提供智能服务策略：
    
    客户反馈: "{customer_text}"
    
    意图分析结果:
    - 主要意图: {intent_analysis.主要意图}
    - 紧急程度: {intent_analysis.紧急程度}
    - 问题类型: {intent_analysis.问题类型}
    - 情感强度: {intent_analysis.情感强度:.2f}
    - 关键词: {', '.join(intent_analysis.关键词)}
    
    请提供：
    1. 意图深度分析和客户真实需求识别
    2. 最佳处理策略和优先级安排
    3. 话术优化建议和个性化调整
    4. 预期服务效果评估
    5. 服务改进机会和最佳实践
    """)
    
    return result