"""Agent 实现模块 - 整合多个工具进行决策"""

from typing import List, Dict, Any, Optional
from deepseek_integrator import DeepSeekIntegrator
from polars_data_processor import PolarsDataProcessor, SentimentPrediction
from enhanced_sentiment_analyzer import EnhancedAirlineSentimentAnalyzer

class AirlineCrisisAgent:
    """航空公司危机处理Agent"""
    
    def __init__(self, data_path: str):
        """初始化Agent"""
        self.data_processor = PolarsDataProcessor(data_path)
        self.deepseek_integrator = DeepSeekIntegrator()
        self.sentiment_analyzer = EnhancedAirlineSentimentAnalyzer()
        self.tools = {
            "analyze_sentiment": self.analyze_sentiment,
            "explain_risk_factors": self.explain_risk_factors,
            "generate_crisis_plan": self.generate_crisis_plan,
            "customer_service_agent": self.customer_service_agent
        }
    
    def analyze_sentiment(self, tweet_text: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """分析情感与危机评估"""
        # 使用情感分析器
        result = self.sentiment_analyzer.analyze_sentiment(tweet_text)
        
        # 计算危机等级
        risk_level = "low"
        if result["sentiment"] == "negative" and result["confidence"] > 0.7:
            risk_level = "high"
        elif result["sentiment"] == "negative":
            risk_level = "medium"
        
        return {
            "sentiment": result["sentiment"],
            "confidence": result["confidence"],
            "risk_level": risk_level,
            "crisis_level": "紧急" if risk_level == "high" else "中等" if risk_level == "medium" else "低"
        }
    
    def explain_risk_factors(self, tweet_text: str, sentiment_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """解释风险影响因素"""
        if not sentiment_result:
            sentiment_result = self.analyze_sentiment(tweet_text)
        
        # 识别风险因素
        risk_factors = []
        
        # 检查关键词
        negative_keywords = ["延误", "取消", "行李", "丢失", "服务", "态度", "差", "糟糕"]
        for keyword in negative_keywords:
            if keyword in tweet_text:
                risk_factors.append({
                    "因素": keyword,
                    "权重": 0.2
                })
        
        # 基于情感强度
        if sentiment_result["confidence"] > 0.8:
            risk_factors.append({
                "因素": "情感强度高",
                "权重": 0.3
            })
        
        return {
            "risk_factors": risk_factors,
            "total_risk_score": sum(factor["权重"] for factor in risk_factors)
        }
    
    def generate_crisis_plan(self, issue_type: str, severity: str) -> Dict[str, Any]:
        """生成危机处置方案"""
        # 使用DeepSeek生成危机处置方案
        event_details = f"问题类型: {issue_type}, 严重程度: {severity}"
        pr_statement = self.deepseek_integrator.generate_pr_statement(event_details)
        
        return {
            "问题分类": issue_type,
            "严重程度": severity,
            "处置方案": pr_statement,
            "建议措施": [
                "立即联系乘客说明情况",
                "启动相应的应急机制",
                "提供合理的赔偿方案",
                "后续跟进确保问题解决"
            ]
        }
    
    def customer_service_agent(self, customer_feedback: str, history: Optional[List[str]] = None) -> str:
        """智能客服响应"""
        # 分析情感
        sentiment_result = self.analyze_sentiment(customer_feedback)
        
        # 生成客服响应
        prompt = f"""
        请根据以下客户反馈生成智能客服响应：
        
        客户反馈：{customer_feedback}
        情感分析结果：{sentiment_result["sentiment"]}
        情感置信度：{sentiment_result["confidence"]}
        
        请生成一个专业、友好的客服响应，包括：
        1. 对客户反馈的理解
        2. 相应的解决方案
        3. 后续跟进措施
        
        请使用中文回复。
        """
        
        # 使用DeepSeek生成响应
        response = self.deepseek_integrator._call_api(prompt)
        return response["choices"][0]["message"]["content"]
    
    def run(self, tweet_text: str) -> Dict[str, Any]:
        """运行完整的决策流程"""
        # 1. 分析情感
        sentiment_result = self.analyze_sentiment(tweet_text)
        
        # 2. 解释风险因素
        risk_result = self.explain_risk_factors(tweet_text, sentiment_result)
        
        # 3. 生成危机处置方案
        issue_type = "服务质量" if "服务" in tweet_text else "航班延误" if "延误" in tweet_text else "其他问题"
        severity = "严重" if sentiment_result["risk_level"] == "high" else "中等" if sentiment_result["risk_level"] == "medium" else "轻微"
        crisis_plan = self.generate_crisis_plan(issue_type, severity)
        
        # 4. 生成客服响应
        cs_response = self.customer_service_agent(tweet_text)
        
        return {
            "sentiment_analysis": sentiment_result,
            "risk_analysis": risk_result,
            "crisis_plan": crisis_plan,
            "customer_service_response": cs_response
        }

# 示例用法
if __name__ == "__main__":
    print("初始化航空公司危机处理Agent...")
    agent = AirlineCrisisAgent("../data/Tweets.csv")
    print("Agent初始化完成!")
    
    # 测试案例
    test_tweet = "我的航班延误了4个小时，行李还丢失了，客服态度极差！"
    print(f"\n测试推文: {test_tweet}")
    
    # 运行Agent
    result = agent.run(test_tweet)
    
    print("\n=== 情感分析结果 ===")
    print(f"情感倾向: {result['sentiment_analysis']['sentiment']}")
    print(f"置信度: {result['sentiment_analysis']['confidence']}")
    print(f"危机等级: {result['sentiment_analysis']['crisis_level']}")
    
    print("\n=== 风险因素分析 ===")
    for factor in result['risk_analysis']['risk_factors']:
        print(f"{factor['因素']}: 权重 {factor['权重']}")
    
    print("\n=== 危机处置方案 ===")
    print(f"问题分类: {result['crisis_plan']['问题分类']}")
    print(f"严重程度: {result['crisis_plan']['严重程度']}")
    print("建议措施:")
    for measure in result['crisis_plan']['建议措施']:
        print(f"- {measure}")
    
    print("\n=== 智能客服响应 ===")
    print(result['customer_service_response'])