"""增强版推文情感分析 Agent

支持 DeepSeek API 和传统 ML 模型的混合模式，提供更智能的分析能力。
"""

import os
from pathlib import Path
from typing import Optional, Literal
import asyncio

from pydantic import BaseModel, Field

from src.deepseek_agent import DeepSeekTweetAgent, TweetAnalysisResult as DeepSeekResult
from src.train_tweet_ultimate import load_model as load_ultimate_model


class AnalysisMode:
    """分析模式枚举"""
    DEEPSEEK = "deepseek"
    TRADITIONAL = "traditional"
    HYBRID = "hybrid"


class EnhancedSentimentClassification(BaseModel):
    """增强版情感分类结果"""
    sentiment: str = Field(description="情感类别: negative/neutral/positive")
    confidence: float = Field(description="置信度 (0-1)")
    reasoning: str = Field(description="情感判断的推理过程")
    key_factors: list[str] = Field(description="影响情感判断的关键因素")
    analysis_mode: str = Field(description="使用的分析模式: deepseek/traditional/hybrid")


class EnhancedDisposalPlan(BaseModel):
    """增强版处置方案"""
    priority: str = Field(description="处理优先级: high/medium/low")
    action_type: str = Field(description="行动类型: response/investigate/monitor/ignore")
    suggested_response: Optional[str] = Field(description="建议回复内容", default=None)
    follow_up_actions: list[str] = Field(description="后续行动建议")
    reasoning: str = Field(description="处置方案制定的理由")


class EnhancedTweetAnalysisResult(BaseModel):
    """增强版推文分析结果"""
    tweet_text: str = Field(description="原始推文文本")
    airline: str = Field(description="航空公司")
    classification: EnhancedSentimentClassification = Field(description="情感分类结果")
    disposal_plan: EnhancedDisposalPlan = Field(description="处置方案")
    processing_time: float = Field(description="处理耗时（秒）")
    api_used: bool = Field(description="是否使用了 API")


class EnhancedTweetSentimentAgent:
    """增强版推文情感分析 Agent
    
    支持 DeepSeek API 和传统 ML 模型的混合模式。
    """
    
    def __init__(self, default_mode: str = AnalysisMode.HYBRID):
        """初始化 Agent
        
        Args:
            default_mode: 默认分析模式 (deepseek/traditional/hybrid)
        """
        self.default_mode = default_mode
        
        # 初始化传统 ML 模型
        self.traditional_model = None
        try:
            self.traditional_model = load_ultimate_model()
            print("✅ 传统 ML 模型加载成功")
        except Exception as e:
            print(f"⚠️ 传统 ML 模型加载失败: {e}")
        
        # 初始化 DeepSeek API 客户端
        self.deepseek_agent = None
        try:
            self.deepseek_agent = DeepSeekTweetAgent()
            print("✅ DeepSeek API 客户端初始化成功")
        except Exception as e:
            print(f"⚠️ DeepSeek API 客户端初始化失败: {e}")
    
    def _traditional_classify(self, text: str, airline: str) -> EnhancedSentimentClassification:
        """传统 ML 模型分类"""
        if not self.traditional_model:
            raise ValueError("传统 ML 模型未加载")
        
        import numpy as np
        
        # 预测
        sentiment = self.traditional_model.predict(np.array([text]), np.array([airline]))[0]
        
        # 预测概率
        proba = self.traditional_model.predict_proba(np.array([text]), np.array([airline]))[0]
        
        # 获取预测类别的置信度
        sentiment_idx = self.traditional_model.label_encoder.transform([sentiment])[0]
        confidence = float(proba[sentiment_idx])
        
        # 生成简单解释
        reasoning = f"基于传统机器学习模型预测，情感倾向为{sentiment}，置信度{confidence:.1%}。"
        
        # 提取关键词（简化版）
        key_factors = [f"模型预测置信度: {confidence:.1%}", f"航空公司: {airline}"]
        
        return EnhancedSentimentClassification(
            sentiment=sentiment,
            confidence=confidence,
            reasoning=reasoning,
            key_factors=key_factors,
            analysis_mode=AnalysisMode.TRADITIONAL
        )
    
    async def _deepseek_classify(self, text: str, airline: str) -> EnhancedSentimentClassification:
        """DeepSeek API 分类"""
        if not self.deepseek_agent:
            raise ValueError("DeepSeek API 客户端未初始化")
        
        result = await self.deepseek_agent.analyze_sentiment(text, airline)
        
        return EnhancedSentimentClassification(
            sentiment=result.sentiment,
            confidence=result.confidence,
            reasoning=result.reasoning,
            key_factors=result.key_factors,
            analysis_mode=AnalysisMode.DEEPSEEK
        )
    
    def _hybrid_classify(self, text: str, airline: str, traditional_result, deepseek_result) -> EnhancedSentimentClassification:
        """混合模式分类"""
        
        # 简单的混合策略：优先使用 DeepSeek，如果失败则使用传统模型
        if deepseek_result.confidence >= 0.7:
            # DeepSeek 置信度高，使用 DeepSeek 结果
            return deepseek_result
        else:
            # DeepSeek 置信度低，使用传统模型结果
            return traditional_result
    
    def _generate_disposal_plan(self, text: str, airline: str, classification: EnhancedSentimentClassification) -> EnhancedDisposalPlan:
        """生成处置方案"""
        
        sentiment = classification.sentiment
        confidence = classification.confidence
        
        # 基于情感和置信度确定优先级和行动类型
        if sentiment == "negative":
            if confidence >= 0.8:
                priority = "high"
                action_type = "response"
                suggested_response = self._generate_negative_response(text, airline)
                follow_up_actions = [
                    "记录客户投诉详情",
                    "转交相关部门处理",
                    "跟进处理进度",
                    "在24小时内给予反馈",
                ]
                reasoning = "负面情感且置信度高，需要立即响应和处理"
            else:
                priority = "medium"
                action_type = "investigate"
                suggested_response = None
                follow_up_actions = [
                    "进一步核实情况",
                    "根据核实结果决定是否需要回复",
                ]
                reasoning = "负面情感但置信度一般，需要进一步调查"
        elif sentiment == "positive":
            if confidence >= 0.8:
                priority = "low"
                action_type = "response"
                suggested_response = self._generate_positive_response(text, airline)
                follow_up_actions = [
                    "感谢客户反馈",
                    "分享正面评价至内部团队",
                    "考虑在官方渠道展示",
                ]
                reasoning = "正面情感且置信度高，适合回复感谢"
            else:
                priority = "low"
                action_type = "monitor"
                suggested_response = None
                follow_up_actions = [
                    "持续关注该用户后续动态",
                ]
                reasoning = "正面情感但置信度一般，保持关注即可"
        else:  # neutral
            if "?" in text or "help" in text.lower():
                priority = "medium"
                action_type = "response"
                suggested_response = self._generate_neutral_response(text, airline)
                follow_up_actions = [
                    "提供准确信息",
                    "确保客户问题得到解答",
                ]
                reasoning = "中性情感但包含询问，需要提供帮助"
            else:
                priority = "low"
                action_type = "monitor"
                suggested_response = None
                follow_up_actions = [
                    "持续关注",
                ]
                reasoning = "中性情感，保持常规关注"
        
        return EnhancedDisposalPlan(
            priority=priority,
            action_type=action_type,
            suggested_response=suggested_response,
            follow_up_actions=follow_up_actions,
            reasoning=reasoning
        )
    
    def _generate_negative_response(self, text: str, airline: str) -> str:
        """生成负面情感回复"""
        responses = [
            f"感谢您的反馈。我们非常重视您提到的问题，将立即进行调查并尽快给您答复。",
            f"对于您的不愉快体验，我们深表歉意。请私信我们详细情况，我们将全力为您解决。",
            f"收到您的反馈，我们对此感到抱歉。相关部门已介入，将尽快处理并给您满意的答复。",
        ]
        return responses[hash(text) % len(responses)]
    
    def _generate_positive_response(self, text: str, airline: str) -> str:
        """生成正面情感回复"""
        responses = [
            f"感谢您的认可和支持！我们会继续努力为您提供更好的服务。",
            f"很高兴听到您的正面反馈！您的满意是我们前进的动力。",
            f"感谢您的分享！我们会将您的反馈传达给团队，激励我们做得更好。",
        ]
        return responses[hash(text) % len(responses)]
    
    def _generate_neutral_response(self, text: str, airline: str) -> str:
        """生成中性情感回复"""
        responses = [
            f"感谢您的询问。请问您需要了解哪方面的信息？我们将竭诚为您解答。",
            f"收到您的问题。请提供更多细节，以便我们更好地为您提供帮助。",
        ]
        return responses[hash(text) % len(responses)]
    
    async def analyze(self, text: str, airline: str, mode: Optional[str] = None) -> EnhancedTweetAnalysisResult:
        """完整分析流程
        
        Args:
            text: 推文文本
            airline: 航空公司
            mode: 分析模式 (deepseek/traditional/hybrid)
            
        Returns:
            完整分析结果
        """
        import time
        start_time = time.time()
        
        analysis_mode = mode or self.default_mode
        api_used = False
        
        # 1. 情感分类
        if analysis_mode == AnalysisMode.TRADITIONAL:
            classification = self._traditional_classify(text, airline)
        elif analysis_mode == AnalysisMode.DEEPSEEK:
            classification = await self._deepseek_classify(text, airline)
            api_used = True
        else:  # hybrid
            # 并行执行两种分析
            traditional_task = asyncio.to_thread(self._traditional_classify, text, airline)
            deepseek_task = self._deepseek_classify(text, airline)
            
            traditional_result, deepseek_result = await asyncio.gather(
                traditional_task, deepseek_task, return_exceptions=True
            )
            
            # 处理异常情况
            if isinstance(traditional_result, Exception):
                print(f"传统模型分析失败: {traditional_result}")
                traditional_result = None
            
            if isinstance(deepseek_result, Exception):
                print(f"DeepSeek API 分析失败: {deepseek_result}")
                deepseek_result = None
            
            if deepseek_result:
                api_used = True
            
            # 混合策略
            if traditional_result and deepseek_result:
                classification = self._hybrid_classify(text, airline, traditional_result, deepseek_result)
            elif deepseek_result:
                classification = deepseek_result
            elif traditional_result:
                classification = traditional_result
            else:
                raise ValueError("所有分析模式都失败了")
        
        # 2. 生成处置方案
        disposal_plan = self._generate_disposal_plan(text, airline, classification)
        
        # 3. 计算处理时间
        processing_time = time.time() - start_time
        
        # 返回完整结果
        return EnhancedTweetAnalysisResult(
            tweet_text=text,
            airline=airline,
            classification=classification,
            disposal_plan=disposal_plan,
            processing_time=processing_time,
            api_used=api_used
        )


def analyze_tweet(text: str, airline: str, mode: str = "hybrid") -> EnhancedTweetAnalysisResult:
    """同步版本的推文分析函数（兼容原有接口）
    
    Args:
        text: 推文文本
        airline: 航空公司
        mode: 分析模式 (deepseek/traditional/hybrid)
        
    Returns:
        分析结果
    """
    agent = EnhancedTweetSentimentAgent()
    return asyncio.run(agent.analyze(text, airline, mode))


def analyze_tweet_ultimate(text: str, mode: str = "traditional") -> EnhancedTweetAnalysisResult:
    """终极版本推文分析函数 - 完全无需航空公司参数
    
    Args:
        text: 推文文本
        mode: 分析模式 (traditional)
        
    Returns:
        分析结果
    """
    agent = EnhancedTweetSentimentAgent()
    
    # 自动检测航空公司或使用通用标识
    airline = "通用航空公司"
    
    # 简单的航空公司检测逻辑
    airline_keywords = {
        "united": "United Airlines",
        "delta": "Delta Air Lines", 
        "american": "American Airlines",
        "southwest": "Southwest Airlines",
        "jetblue": "JetBlue Airways",
        "air china": "中国国际航空",
        "china eastern": "中国东方航空", 
        "china southern": "中国南方航空"
    }
    
    text_lower = text.lower()
    for keyword, airline_name in airline_keywords.items():
        if keyword in text_lower:
            airline = airline_name
            break
    
    return asyncio.run(agent.analyze(text, airline, mode))