"""航空公司情感分析智能Agent应用"""

import os
import sys
from pathlib import Path
from typing import List, Dict, Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from dotenv import load_dotenv
import joblib
import pandas as pd

# 添加项目根目录到Python路径
sys.path.append(str(Path(__file__).parent.parent))

from src.data import DataProcessor

# 加载环境变量
load_dotenv()


class DisposalPlan(BaseModel):
    """客服处置方案结构化输出"""
    问题分类: str = Field(description="问题类型，如'航班延误'、'行李问题'、'服务态度'等")
    严重程度: Literal["紧急", "重要", "常规"] = Field(description="问题紧急程度")
    建议措施: List[str] = Field(description="具体的处理建议和行动项")
    时间线: Dict[str, str] = Field(description="各阶段处理时间安排")
    责任部门: str = Field(description="主要负责部门")
    预期解决时间: str = Field(description="预计问题解决时间")


class SentimentAnalyzer:
    """情感分析器"""
    
    def __init__(self):
        self.model_path = Path("models/sentiment_model.pkl")
        self.feature_names_path = Path("models/feature_names.pkl")
        
        if self.model_path.exists():
            self.model = joblib.load(self.model_path)
            self.feature_names = joblib.load(self.feature_names_path)
        else:
            raise FileNotFoundError("模型文件不存在，请先运行训练脚本")
    
    def is_chinese_text(self, text: str) -> bool:
        """检测是否为中文文本"""
        chinese_chars = sum(1 for char in str(text) if '\u4e00' <= char <= '\u9fff')
        return chinese_chars / max(len(str(text)), 1) > 0.3  # 30%以上为中文字符
    
    def analyze_chinese_sentiment(self, text: str) -> Dict:
        """中文情感分析（基于关键词匹配）"""
        text_lower = str(text).lower()
        
        # 中文负面情感关键词
        negative_keywords_cn = [
            '难吃', '太难吃', '糟糕', '太糟糕', '差', '很差', '非常差',
            '失望', '很失望', '非常失望', '生气', '很生气', '非常生气',
            '讨厌', '很讨厌', '非常讨厌', '恶心', '很恶心', '非常恶心',
            '延误', '取消', '丢失', '损坏', '破损', '故障', '问题'
        ]
        
        # 中文正面情感关键词
        positive_keywords_cn = [
            '好吃', '很好吃', '美味', '很美味', '好', '很好', '非常好',
            '满意', '很满意', '非常满意', '喜欢', '很喜欢', '非常喜欢',
            '棒', '很棒', '非常棒', '优秀', '很优秀', '非常优秀',
            '准时', '顺利', '舒适', '干净', '专业', '热情'
        ]
        
        # 计算关键词匹配
        negative_count = sum(1 for word in negative_keywords_cn if word in text_lower)
        positive_count = sum(1 for word in positive_keywords_cn if word in text_lower)
        
        # 情感判断逻辑
        if negative_count > positive_count:
            sentiment = 'negative'
            confidence = min(0.95, 0.7 + negative_count * 0.1)
        elif positive_count > negative_count:
            sentiment = 'positive'
            confidence = min(0.95, 0.7 + positive_count * 0.1)
        else:
            sentiment = 'neutral'
            confidence = 0.8
        
        return {
            'sentiment': sentiment,
            'confidence': confidence,
            'probabilities': {
                'negative': 0.33 if sentiment == 'negative' else 0.1,
                'neutral': 0.33 if sentiment == 'neutral' else 0.1,
                'positive': 0.33 if sentiment == 'positive' else 0.1
            }
        }
    
    def predict_sentiment(self, text: str, airline: str = "unknown") -> Dict:
        """预测推文情感"""
        
        # 如果是中文文本，使用中文情感分析
        if self.is_chinese_text(text):
            return self.analyze_chinese_sentiment(text)
        
        # 英文文本使用原模型
        processor = DataProcessor("data/Tweets.csv")
        
        # 创建测试数据（包含所有必需列）
        test_data = {
            'text': [text],
            'airline': [airline],
            'airline_sentiment_confidence': [0.8],  # 默认置信度
            'negativereason': [None],  # 添加negativereason列
            'tweet_created': [pd.Timestamp.now()]
        }
        
        df_test = pd.DataFrame(test_data)
        df_processed = processor.extract_features(df_test)
        
        # 准备特征
        feature_cols = (self.feature_names['numeric_features'] + 
                       self.feature_names['categorical_features'] + 
                       [self.feature_names['text_feature']])
        
        X_test = df_processed[feature_cols]
        
        # 预测
        prediction = self.model.predict(X_test)[0]
        probability = self.model.predict_proba(X_test)[0]
        
        return {
            'sentiment': prediction,
            'confidence': max(probability),
            'probabilities': dict(zip(self.model.classes_, probability))
        }


# 创建AI智能客服Agent（使用DeepSeek API）
agent = Agent(
    'deepseek:deepseek-chat',
    system_prompt="""
    你是一个航空公司客户服务专家，专门处理社交媒体上的客户反馈。
    根据推文内容和情感分析结果，生成结构化的客服处置方案。
    
    请根据以下信息生成处置方案：
    1. 推文内容反映的具体问题
    2. 情感分析结果（正面/中性/负面）
    3. 航空公司和问题上下文
    4. 行业最佳实践
    
    输出必须是结构化的JSON格式。
    """,
    output_type=DisposalPlan
)


@agent.tool
async def analyze_tweet_sentiment(ctx, text: str, airline: str = "unknown") -> Dict:
    """分析推文情感"""
    analyzer = SentimentAnalyzer()
    return analyzer.predict_sentiment(text, airline)


@agent.tool
async def get_airline_info(ctx, airline: str) -> Dict:
    """获取航空公司信息"""
    # 模拟航空公司信息
    airline_info = {
        "united": {"客服电话": "1-800-864-8331", "紧急联系人": "客服经理", "响应时间": "2小时内"},
        "american": {"客服电话": "1-800-433-7300", "紧急联系人": "运营总监", "响应时间": "1小时内"},
        "delta": {"客服电话": "1-800-221-1212", "紧急联系人": "客户关系部", "响应时间": "4小时内"},
        "southwest": {"客服电话": "1-800-435-9792", "紧急联系人": "社交媒体团队", "响应时间": "6小时内"},
        "us airways": {"客服电话": "1-800-428-4322", "紧急联系人": "服务质量部", "响应时间": "3小时内"}
    }
    
    return airline_info.get(airline.lower(), {
        "客服电话": "待确认", 
        "紧急联系人": "客服主管", 
        "响应时间": "24小时内"
    })


async def generate_disposal_plan(tweet_text: str, airline: str = "unknown") -> DisposalPlan:
    """生成客服处置方案"""
    
    result = await agent.run(
        f"""
        请为以下推文生成客服处置方案：
        
        推文内容: "{tweet_text}"
        航空公司: {airline}
        
        请分析问题严重程度，制定具体的处理措施和时间安排。
        """
    )
    
    # pydantic-ai新版本直接返回结构化数据
    return result


async def main():
    """主函数 - 演示Agent功能"""
    print("=== 航空公司情感分析智能Agent ===\n")
    
    # 测试用例
    test_tweets = [
        ("@United my flight was delayed for 3 hours and no one gave us any information! This is terrible service!", "united"),
        ("Just had a wonderful flight with @Delta. The crew was amazing and everything was perfect!", "delta"),
        ("@AmericanAir lost my luggage and now I have no clothes for my business meeting. Very disappointed.", "american")
    ]
    
    for i, (tweet, airline) in enumerate(test_tweets, 1):
        print(f"\n--- 测试用例 {i} ---")
        print(f"推文: {tweet}")
        print(f"航空公司: {airline}")
        
        try:
            # 情感分析
            analyzer = SentimentAnalyzer()
            sentiment_result = analyzer.predict_sentiment(tweet, airline)
            print(f"情感分析: {sentiment_result['sentiment']} (置信度: {sentiment_result['confidence']:.3f})")
            
            # 生成处置方案
            disposal_plan = await generate_disposal_plan(tweet, airline)
            print("\n处置方案:")
            print(f"问题分类: {disposal_plan.问题分类}")
            print(f"严重程度: {disposal_plan.严重程度}")
            print(f"责任部门: {disposal_plan.责任部门}")
            print(f"预期解决时间: {disposal_plan.预期解决时间}")
            print("建议措施:")
            for j, measure in enumerate(disposal_plan.建议措施, 1):
                print(f"  {j}. {measure}")
            print("时间线:")
            for stage, action in disposal_plan.时间线.items():
                print(f"  {stage}: {action}")
                
        except Exception as e:
            print(f"处理错误: {e}")


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())