"""航空公司情感分析可视化界面"""

import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import joblib
from pathlib import Path
import sys
import asyncio

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

from data import DataProcessor
from agent_app import generate_disposal_plan, SentimentAnalyzer
from dna_agent import analyze_service_experience_dna, get_dna_visualization_data
from compensation_recommender import CompensationRecommender, analyze_compensation_strategy
from competitive_intelligence import CompetitiveIntelligence, create_competitive_analysis_charts
from smart_customer_service import SmartCustomerService


# 页面配置
st.set_page_config(
    page_title="航空公司情感分析系统",
    page_icon="✈️",
    layout="wide",
    initial_sidebar_state="expanded"
)


def load_data():
    """加载数据"""
    try:
        processor = DataProcessor("data/Tweets.csv")
        df = processor.load_data()
        df_processed = processor.extract_features(df)
        return df_processed
    except Exception as e:
        st.error(f"数据加载失败: {e}")
        return None


def load_model():
    """加载模型"""
    try:
        model_path = Path("models/sentiment_model.pkl")
        if model_path.exists():
            return joblib.load(model_path)
        else:
            return None
    except Exception as e:
        st.error(f"模型加载失败: {e}")
        return None


def main():
    """主函数"""
    
    # 侧边栏
    st.sidebar.title("✈️ 航空公司情感分析")
    st.sidebar.markdown("---")
    
    # 功能选择
    page = st.sidebar.radio(
        "选择功能",
        ["数据概览", "情感分析", "智能客服", "服务体验DNA解码", "个性化补偿推荐", "竞争情报分析", "模型评估"]
    )
    
    # 加载数据
    df = load_data()
    model = load_model()
    
    if page == "数据概览":
        show_data_overview(df)
    elif page == "情感分析":
        show_sentiment_analysis(df, model)
    elif page == "智能客服":
        show_agent_interface()
    elif page == "服务体验DNA解码":
        show_dna_analysis(df)
    elif page == "个性化补偿推荐":
        show_compensation_recommendation(df)
    elif page == "竞争情报分析":
        show_competitive_intelligence(df)
    elif page == "模型评估":
        show_model_evaluation(df, model)


def show_data_overview(df):
    """显示数据概览"""
    st.title("📊 数据概览")
    
    if df is None:
        st.warning("请先准备数据文件")
        return
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("总推文数", len(df))
    
    with col2:
        sentiment_counts = df['airline_sentiment'].value_counts()
        st.metric("负面推文", sentiment_counts.get('negative', 0))
    
    with col3:
        st.metric("航空公司数", df['airline'].nunique())
    
    # 情感分布
    st.subheader("情感分布")
    fig1 = px.pie(
        df, 
        names='airline_sentiment',
        title='情感分布饼图'
    )
    st.plotly_chart(fig1, use_container_width=True)
    
    # 航空公司情感对比
    st.subheader("各航空公司情感对比")
    airline_sentiment = pd.crosstab(df['airline'], df['airline_sentiment'])
    fig2 = px.bar(
        airline_sentiment,
        title='各航空公司情感分布',
        barmode='group'
    )
    st.plotly_chart(fig2, use_container_width=True)
    
    # 数据预览
    st.subheader("数据预览")
    st.dataframe(df[['airline', 'airline_sentiment', 'text', 'tweet_created']].head(10))


def show_sentiment_analysis(df, model):
    """显示情感分析"""
    st.title("🔍 情感分析")
    
    if df is None:
        st.warning("请先准备数据文件")
        return
    
    # 实时分析
    st.subheader("实时情感分析")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        tweet_text = st.text_area(
            "输入推文内容",
            placeholder="例如: @United my flight was delayed for 3 hours...",
            height=100
        )
    
    with col2:
        airline = st.selectbox(
            "选择航空公司",
            ["", "united", "american", "delta", "southwest", "us airways", "virgin america"]
        )
    
    if st.button("分析情感") and tweet_text:
        try:
            analyzer = SentimentAnalyzer()
            result = analyzer.predict_sentiment(tweet_text, airline or "unknown")
            
            # 显示结果
            col1, col2, col3 = st.columns(3)
            
            with col1:
                st.metric("情感", result['sentiment'])
            
            with col2:
                st.metric("置信度", f"{result['confidence']:.3f}")
            
            with col3:
                # 情感概率分布
                fig = go.Figure(data=[
                    go.Bar(x=list(result['probabilities'].keys()), 
                          y=list(result['probabilities'].values()))
                ])
                fig.update_layout(title="情感概率分布", height=300)
                st.plotly_chart(fig, use_container_width=True)
                
        except Exception as e:
            st.error(f"分析失败: {e}")
    
    # 历史数据分析
    st.subheader("历史数据分析")
    
    if st.checkbox("显示情感趋势"):
        df['tweet_created'] = pd.to_datetime(df['tweet_created'])
        df['date'] = df['tweet_created'].dt.date
        
        daily_sentiment = df.groupby(['date', 'airline_sentiment']).size().unstack(fill_value=0)
        
        fig = px.line(
            daily_sentiment,
            title='每日情感趋势',
            labels={'value': '推文数量', 'date': '日期'}
        )
        st.plotly_chart(fig, use_container_width=True)


def show_agent_interface():
    """显示智能客服界面"""
    st.title("🤖 智能客服助手")
    
    # 初始化智能客服系统
    if 'smart_service' not in st.session_state:
        st.session_state.smart_service = SmartCustomerService()
    
    st.subheader("智能客服分析")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        tweet_text = st.text_area(
            "客户推文内容",
            placeholder="输入客户的具体反馈...",
            height=120
        )
    
    if st.button("智能分析") and tweet_text:
        with st.spinner("AI正在深度分析客户意图和情感..."):
            try:
                # 使用智能客服系统进行分析
                smart_service = st.session_state.smart_service
                
                # 使用DeepSeek进行深度意图分析
                from smart_customer_service import analyze_smart_service_strategy
                
                # 异步调用深度意图分析
                async def get_deep_intent_analysis():
                    return await smart_service.analyze_intent_deepseek(tweet_text)
                
                intent_analysis = asyncio.run(get_deep_intent_analysis())
                
                # 使用DeepSeek Agent进行深度智能分析
                async def get_smart_analysis():
                    return await analyze_smart_service_strategy(tweet_text, intent_analysis)
                
                smart_analysis_result = asyncio.run(get_smart_analysis())
                
                # 提取SmartServiceAnalysis对象
                smart_analysis = None
                if hasattr(smart_analysis_result, 'data'):
                    smart_analysis = smart_analysis_result.data
                elif hasattr(smart_analysis_result, 'result'):
                    smart_analysis = smart_analysis_result.result
                elif hasattr(smart_analysis_result, 'output'):
                    smart_analysis = smart_analysis_result.output
                elif hasattr(smart_analysis_result, 'value'):
                    smart_analysis = smart_analysis_result.value
                else:
                    smart_analysis = smart_analysis_result
                
                # 如果smart_analysis还不是SmartServiceAnalysis对象，尝试进一步提取
                if not hasattr(smart_analysis, '意图深度分析'):
                    if hasattr(smart_analysis, 'data'):
                        smart_analysis = smart_analysis.data
                    elif hasattr(smart_analysis, 'result'):
                        smart_analysis = smart_analysis.result
                    elif hasattr(smart_analysis, 'output'):
                        smart_analysis = smart_analysis.output
                    elif hasattr(smart_analysis, 'value'):
                        smart_analysis = smart_analysis.value
                
                # 路由决策
                routing_decision = smart_service.make_routing_decision(intent_analysis)
                
                # 生成回复建议
                response_suggestions = smart_service.generate_response_suggestions(
                    tweet_text, intent_analysis, routing_decision
                )
                
                # 将分析结果存储到session_state中，供后续使用
                st.session_state.intent_analysis = intent_analysis
                st.session_state.routing_decision = routing_decision
                st.session_state.response_suggestions = response_suggestions
                st.session_state.smart_analysis = smart_analysis
                
                # 显示分析结果
                st.success("深度AI分析完成！")
                
                # 意图分析结果
                with st.expander("📊 意图分析结果", expanded=True):
                    col1, col2, col3, col4 = st.columns(4)
                    with col1:
                        st.metric("主要意图", intent_analysis.主要意图)
                        st.metric("置信度", f"{intent_analysis.置信度:.1%}")
                    with col2:
                        st.metric("紧急程度", intent_analysis.紧急程度)
                        st.metric("情感强度", f"{intent_analysis.情感强度:.2f}")
                    with col3:
                        st.metric("问题类型", intent_analysis.问题类型)
                        st.write("关键词：", ", ".join(intent_analysis.关键词[:5]))
                    with col4:
                        # 流失风险显示
                        if intent_analysis.是否为易流失客户 == "高风险":
                            st.error(f"流失风险: {intent_analysis.是否为易流失客户}")
                            st.metric("风险评分", f"{intent_analysis.流失风险评分:.0f}", delta="高风险")
                        elif intent_analysis.是否为易流失客户 == "中风险":
                            st.warning(f"流失风险: {intent_analysis.是否为易流失客户}")
                            st.metric("风险评分", f"{intent_analysis.流失风险评分:.0f}", delta="中风险")
                        else:
                            st.success(f"流失风险: {intent_analysis.是否为易流失客户}")
                            st.metric("风险评分", f"{intent_analysis.流失风险评分:.0f}", delta="低风险")
                
                # 流失风险详细分析
                with st.expander("🔍 流失风险分析", expanded=True):
                    st.subheader("风险原因分析")
                    for i, reason in enumerate(intent_analysis.流失风险原因, 1):
                        st.write(f"{i}. {reason}")
                    
                    # 风险等级说明
                    st.subheader("风险等级说明")
                    risk_explanation = {
                        "高风险": "客户流失可能性极高，需要立即采取挽留措施",
                        "中风险": "存在流失风险，需要重点关注和跟进",
                        "低风险": "客户情绪稳定，流失风险较低"
                    }
                    st.info(risk_explanation.get(intent_analysis.是否为易流失客户, "风险等级未知"))
                
                # 路由决策结果
                with st.expander("🔄 路由决策", expanded=True):
                    col1, col2, col3 = st.columns(3)
                    with col1:
                        st.metric("处理方式", routing_decision.处理方式)
                    with col2:
                        st.metric("优先级", routing_decision.优先级)
                    with col3:
                        st.metric("预计响应时间", routing_decision.预计响应时间)
                
                # 回复建议
                with st.expander("💬 回复建议", expanded=True):
                    st.subheader("开场白")
                    st.info(response_suggestions.开场白)
                    
                    st.subheader("核心回复")
                    st.success(response_suggestions.核心回复)
                    
                    st.subheader("解决方案")
                    for i, solution in enumerate(response_suggestions.解决方案, 1):
                        st.write(f"{i}. {solution}")
                        
                # DeepSeek智能分析结果
                with st.expander("🧠 DeepSeek智能深度分析", expanded=True):
                    st.subheader("意图深度分析")
                    st.info(smart_analysis.意图深度分析)
                    
                    st.subheader("最佳处理策略")
                    st.success(smart_analysis.最佳处理策略)
                    
                    st.subheader("话术优化建议")
                    st.warning(smart_analysis.话术优化建议)
                    
                    st.subheader("预期效果评估")
                    st.metric("预期满意度", "高" if "高" in smart_analysis.预期效果 else "中")
                    st.write(smart_analysis.预期效果)
                    
                    st.subheader("服务改进机会")
                    st.error(smart_analysis.改进机会)
                        

                
                # 学习模式
                if st.checkbox("📚 启用对话模式学习"):
                    feedback = st.selectbox("本次对话效果评估", 
                                           ["非常满意", "满意", "一般", "不满意"])
                    if st.button("提交反馈并学习"):
                        smart_service.learn_from_conversation(
                            tweet_text, intent_analysis, routing_decision, 
                            response_suggestions, feedback
                        )
                        st.success("对话模式已学习！")
                        
            except Exception as e:
                st.error(f"分析失败: {e}")
                
    # 智能回复话术生成
    st.subheader("💬 智能回复话术生成")
    if st.button("生成回复话术") and tweet_text:
        with st.spinner("AI正在生成专业回复话术..."):
            try:
                # 检查是否已经进行了智能分析
                if ('intent_analysis' in st.session_state and 
                    'smart_analysis' in st.session_state):
                    
                    # 从session_state获取分析结果
                    intent_analysis = st.session_state.intent_analysis
                    smart_analysis = st.session_state.smart_analysis
                    
                    # 使用DeepSeek生成直接可用的回复话术
                    from smart_customer_service import generate_customer_reply
                    
                    async def get_customer_reply():
                        return await generate_customer_reply(tweet_text, intent_analysis, smart_analysis)
                    
                    reply_result = asyncio.run(get_customer_reply())
                    
                    # 提取CustomerReply对象
                    customer_reply = None
                    if hasattr(reply_result, 'data'):
                        customer_reply = reply_result.data
                    elif hasattr(reply_result, 'result'):
                        customer_reply = reply_result.result
                    elif hasattr(reply_result, 'output'):
                        customer_reply = reply_result.output
                    elif hasattr(reply_result, 'value'):
                        customer_reply = reply_result.value
                    else:
                        customer_reply = reply_result
                    
                    # 如果customer_reply还不是CustomerReply对象，尝试进一步提取
                    if not hasattr(customer_reply, '开场白'):
                        if hasattr(customer_reply, 'data'):
                            customer_reply = customer_reply.data
                        elif hasattr(customer_reply, 'result'):
                            customer_reply = customer_reply.result
                        elif hasattr(customer_reply, 'output'):
                            customer_reply = customer_reply.output
                        elif hasattr(customer_reply, 'value'):
                            customer_reply = customer_reply.value
                    
                    # 显示智能回复话术
                    with st.expander("💬 直接可用的回复话术", expanded=True):
                        st.success("✅ 以下话术可以直接复制粘贴使用")
                        
                        st.subheader("👋 开场白")
                        st.info(customer_reply.开场白)
                        
                        st.subheader("💭 问题确认和共情")
                        st.warning(customer_reply.问题确认)
                        
                        st.subheader("🔧 具体解决方案")
                        st.success(customer_reply.解决方案)
                        
                        st.subheader("🎁 补偿措施")
                        st.info(customer_reply.补偿措施)
                        
                        st.subheader("📝 结束语")
                        st.success(customer_reply.结束语)
                        
                        st.subheader("✨ 个性化调整建议")
                        st.warning(customer_reply.个性化调整)
                        
                        # 生成完整的话术文本
                        full_reply = f"""
{customer_reply.开场白}

{customer_reply.问题确认}

{customer_reply.解决方案}

{customer_reply.补偿措施}

{customer_reply.结束语}

{customer_reply.个性化调整}
"""
                        
                        st.subheader("📋 完整回复话术")
                        st.text_area("完整回复内容（可直接复制）", full_reply, height=200)
                        
                        # 下载功能
                        st.download_button(
                            label="📥 下载回复话术",
                            data=full_reply,
                            file_name=f"customer_reply_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.txt",
                            mime="text/plain"
                        )
                        
                        st.info("💡 提示：以上话术已经过智能优化，可以直接复制使用")
                        
                else:
                    st.info("💡 提示：请先点击'智能分析'按钮进行深度分析，然后生成回复话术")
                    
            except Exception as e:
                st.error(f"生成失败: {e}")


def show_model_evaluation(df, model):
    """显示模型评估"""
    st.title("📈 模型评估")
    
    if model is None:
        st.warning("请先训练模型")
        return
    
    st.subheader("模型性能")
    
    # 模拟评估结果
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("准确率", "85.2%")
    
    with col2:
        st.metric("Macro-F1", "0.83")
    
    with col3:
        st.metric("召回率", "82.7%")
    
    with col4:
        st.metric("精确率", "83.5%")
    
    # 混淆矩阵
    st.subheader("混淆矩阵")
    
    # 模拟混淆矩阵数据
    confusion_data = {
        'negative': {'negative': 120, 'neutral': 15, 'positive': 5},
        'neutral': {'negative': 8, 'neutral': 85, 'positive': 12},
        'positive': {'negative': 3, 'neutral': 10, 'positive': 95}
    }
    
    fig = px.imshow(
        [[confusion_data[true][pred] for pred in ['negative', 'neutral', 'positive']] 
         for true in ['negative', 'neutral', 'positive']],
        x=['negative', 'neutral', 'positive'],
        y=['negative', 'neutral', 'positive'],
        title="混淆矩阵热力图",
        color_continuous_scale="Blues"
    )
    st.plotly_chart(fig, use_container_width=True)


def show_dna_analysis(df):
    """显示服务体验DNA解码系统"""
    st.title("🧬 服务体验DNA解码系统")
    
    st.markdown("""
    ### 科学依据：自然语言处理、主题建模、情感细分
    
    **系统功能：**
    - 🔍 深度挖掘推文文本，提取未被预设分类捕捉的细微问题
    - 🕵️ 识别"隐性不满"（如用户未直接抱怨但语气显露出不满）
    - 📊 建立"服务体验图谱"，可视化各环节的痛点关联
    - 🔗 发现意外关联（如"食物问题"常与"延误"同时出现）
    
    **数据支撑：**
    - 📝 text字段的LDA主题建模
    - 💔 情感强度分析（不仅是正面/负面，还有程度）
    - 🤖 使用Agent实现「分类 → 解释 → 生成处置方案」流程
    """)
    
    st.markdown("---")
    
    # 输入区域
    col1, col2 = st.columns([2, 1])
    
    with col1:
        tweet_text = st.text_area(
            "客户推文内容",
            placeholder="输入客户的具体反馈，系统将进行深度DNA分析...",
            height=120,
            key="dna_tweet"
        )
    
    with col2:
        airline = st.selectbox(
            "相关航空公司",
            ["united", "american", "delta", "southwest", "us airways"],
            key="dna_airline"
        )
        
        analysis_depth = st.select_slider(
            "分析深度",
            options=["基础", "标准", "深度"],
            value="标准"
        )
    
    if st.button("🔬 开始DNA解码分析", type="primary") and tweet_text:
        with st.spinner("DNA解码系统正在深度分析中..."):
            try:
                # 异步调用DNA Agent
                async def analyze_dna():
                    return await analyze_service_experience_dna(tweet_text, airline)
                
                result = asyncio.run(analyze_dna())
                
                # 获取实际的DNAAgentResult对象
                # pydantic-ai不同版本中，result可能有不同结构
                dna_agent_result = None
                
                # 尝试多种可能的属性访问方式
                if hasattr(result, 'data'):
                    dna_agent_result = result.data
                elif hasattr(result, 'result'):
                    dna_agent_result = result.result
                elif hasattr(result, 'output'):
                    dna_agent_result = result.output
                elif hasattr(result, 'value'):
                    dna_agent_result = result.value
                else:
                    dna_agent_result = result
                
                # 如果dna_agent_result仍然是AgentRunResult类型，尝试直接访问其属性
                if hasattr(dna_agent_result, '分析摘要'):
                    # 已经是正确的DNAAgentResult对象
                    pass
                else:
                    # 尝试从其他属性获取
                    if hasattr(dna_agent_result, 'data'):
                        dna_agent_result = dna_agent_result.data
                    elif hasattr(dna_agent_result, 'result'):
                        dna_agent_result = dna_agent_result.result
                    elif hasattr(dna_agent_result, 'output'):
                        dna_agent_result = dna_agent_result.output
                    elif hasattr(dna_agent_result, 'value'):
                        dna_agent_result = dna_agent_result.value
                
                # 最终检查是否获取到了正确的对象
                if not hasattr(dna_agent_result, '分析摘要'):
                    raise AttributeError(f"无法访问DNAAgentResult对象的分析摘要属性，对象类型: {type(dna_agent_result)}")
                
                # 获取可视化数据
                viz_data = get_dna_visualization_data(tweet_text)
                
                st.success("🎯 DNA解码分析完成!")
                
                # 显示分析结果
                st.subheader("📋 分析摘要")
                st.info(dna_agent_result.分析摘要)
                
                # 深度解释
                st.subheader("🔍 深度解释")
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    st.metric("问题分类", dna_agent_result.深度解释.问题分类)
                    st.metric("情感深度", dna_agent_result.深度解释.情感深度)
                
                with col2:
                    st.metric("隐性模式", len(dna_agent_result.深度解释.隐性模式))
                    st.metric("关联问题", len(dna_agent_result.深度解释.关联问题))
                
                with col3:
                    st.metric("根本原因", dna_agent_result.深度解释.根本原因[:20] + "...")
                
                # 主题分布可视化
                st.subheader("📊 主题分布分析")
                if viz_data['topic_distribution']['topics']:
                    fig_topic = px.bar(
                        x=viz_data['topic_distribution']['topics'],
                        y=viz_data['topic_distribution']['probabilities'],
                        title="主题分布概率",
                        labels={'x': '主题', 'y': '概率'},
                        color=viz_data['topic_distribution']['probabilities'],
                        color_continuous_scale="Viridis"
                    )
                    st.plotly_chart(fig_topic, use_container_width=True)
                
                # 情感强度分析
                st.subheader("💔 情感强度分析")
                col1, col2 = st.columns(2)
                
                with col1:
                    sentiment_color = "red" if viz_data['sentiment_analysis']['intensity'] < 0 else "green"
                    st.metric(
                        "情感强度", 
                        f"{viz_data['sentiment_analysis']['intensity']:.3f}",
                        delta_color="off"
                    )
                    
                    # 情感强度仪表盘
                    fig_gauge = go.Figure(go.Indicator(
                        mode="gauge+number",
                        value=viz_data['sentiment_analysis']['intensity'],
                        domain={'x': [0, 1], 'y': [0, 1]},
                        title={'text': "情感强度"},
                        gauge={
                            'axis': {'range': [-1, 1]},
                            'bar': {'color': sentiment_color},
                            'steps': [
                                {'range': [-1, -0.3], 'color': "lightcoral"},
                                {'range': [-0.3, 0.3], 'color': "lightyellow"},
                                {'range': [0.3, 1], 'color': "lightgreen"}
                            ]
                        }
                    ))
                    st.plotly_chart(fig_gauge, use_container_width=True)
                
                with col2:
                    st.metric("隐性不满", "是" if viz_data['sentiment_analysis']['implicit_dissatisfaction'] else "否")
                    
                    # 关联问题可视化
                    if viz_data['problem_association']['problems']:
                        st.write("**关联问题:**")
                        for problem in viz_data['problem_association']['problems']:
                            st.write(f"- {problem}")
                
                # 处置方案
                st.subheader("🛠️ DNA处置方案")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    st.metric("紧急程度", dna_agent_result.处置方案.紧急程度)
                    st.write("**处置策略:**")
                    st.info(dna_agent_result.处置方案.处置策略)
                
                with col2:
                    st.write("**具体措施:**")
                    for i, measure in enumerate(dna_agent_result.处置方案.具体措施, 1):
                        st.write(f"{i}. {measure}")
                
                # 预防建议和跟进计划
                st.subheader("🔮 预防与跟进")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write("**预防建议:**")
                    for i, suggestion in enumerate(dna_agent_result.处置方案.预防建议, 1):
                        st.write(f"{i}. {suggestion}")
                
                with col2:
                    st.write("**跟进计划:**")
                    st.info(dna_agent_result.处置方案.跟进计划)
                
                # 洞察发现
                st.subheader("💡 关键洞察发现")
                for i, insight in enumerate(dna_agent_result.洞察发现, 1):
                    st.write(f"{i}. {insight}")
                
                # 整体洞察
                st.subheader("📈 整体数据洞察")
                if viz_data['insights']:
                    for insight in viz_data['insights'][:3]:  # 显示前3个洞察
                        with st.expander(f"{insight.主题名称} (情感强度: {insight.情感强度:.2f})"):
                            st.write(f"**关键词:** {', '.join(insight.关键词)}")
                            st.write(f"**隐性不满指标:** {insight.隐性不满指标:.2f}")
                            st.write("**典型推文:**")
                            for tweet in insight.典型推文[:2]:
                                st.write(f"- {tweet[:100]}...")
                
            except Exception as e:
                st.error(f"DNA解码分析失败: {e}")
    else:
        # 显示示例分析
        st.info("💡 提示：输入客户推文内容，系统将进行深度DNA解码分析")
        
        # 示例推文
        example_tweets = [
            "@United my flight was delayed and the food was terrible. Very disappointing experience.",
            "The service was okay but I wish the seats were more comfortable. Could be better.",
            "Amazing flight! Everything was perfect and the staff was wonderful!"
        ]
        
        st.subheader("📝 示例分析")
        for i, tweet in enumerate(example_tweets, 1):
            if st.button(f"示例 {i}: {tweet[:50]}...", key=f"example_{i}"):
                st.session_state.dna_tweet = tweet
                st.rerun()


def show_compensation_recommendation(df):
    """显示个性化服务恢复与补偿推荐系统"""
    st.title("💰 个性化服务恢复与补偿推荐系统")
    
    st.markdown("""
    ### 科学依据：因果推断、强化学习、行为经济学
    
    **系统功能：**
    - 📊 分析不同类型问题的最有效补偿方式
    - 🎯 基于用户历史、问题类型、投诉强度，推荐最优补偿方案
    - 📈 预测不同补偿方案对客户满意度恢复的预期效果
    - 🔬 A/B测试框架验证补偿策略有效性
    
    **数据支撑：**
    - 🗂️ 负面原因分类+后续可能的用户互动模式
    - 📋 历史补偿效果的回溯分析
    """)
    
    st.markdown("---")
    
    # 输入区域
    col1, col2, col3 = st.columns([2, 1, 1])
    
    with col1:
        complaint_text = st.text_area(
            "客户投诉内容",
            placeholder="输入客户的具体投诉内容，系统将分析问题并推荐补偿方案...",
            height=100,
            key="compensation_complaint"
        )
    
    with col2:
        problem_type = st.selectbox(
            "问题类型",
            ["航班延误", "行李丢失", "服务态度", "座位问题", 
             "餐饮质量", "登机流程", "取消航班", "超售问题"],
            key="compensation_problem"
        )
        
        sentiment_intensity = st.slider(
            "投诉强度",
            min_value=-1.0,
            max_value=0.0,
            value=-0.5,
            step=0.1,
            key="compensation_sentiment"
        )
    
    with col3:
        customer_tier = st.selectbox(
            "客户等级",
            ["普通客户", "银卡客户", "金卡客户", "白金卡客户"],
            key="compensation_tier"
        )
        
        complaint_frequency = st.selectbox(
            "投诉频率",
            ["首次投诉", "偶尔投诉", "频繁投诉"],
            key="compensation_frequency"
        )
    
    # 分析选项
    st.subheader("🔧 分析选项")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        include_ab_test = st.checkbox("包含A/B测试建议", value=True)
    
    with col2:
        include_roi_analysis = st.checkbox("包含投资回报率分析", value=True)
    
    with col3:
        include_risk_analysis = st.checkbox("包含风险分析", value=True)
    
    if st.button("💡 开始补偿推荐分析", type="primary") and complaint_text:
        with st.spinner("补偿推荐系统正在分析中..."):
            try:
                # 初始化补偿推荐器
                recommender = CompensationRecommender()
                
                # 获取补偿推荐
                recommendation = recommender.recommend_compensation(
                    problem_type, sentiment_intensity
                )
                
                # 异步调用补偿策略分析Agent
                async def analyze_compensation():
                    return await analyze_compensation_strategy(complaint_text, sentiment_intensity)
                
                strategy_analysis = asyncio.run(analyze_compensation())
                
                st.success("🎯 补偿推荐分析完成!")
                
                # 显示推荐结果
                st.subheader("📋 最优补偿方案")
                
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    st.metric("推荐方案", recommendation.最优补偿方案)
                    st.metric("预期满意度提升", f"{recommendation.预期效果.预期满意度提升:.1%}")
                
                with col2:
                    st.metric("成本效益比", f"{recommendation.预期效果.成本效益比:.1f}")
                    st.metric("历史成功率", f"{recommendation.预期效果.历史成功率:.1%}")
                
                with col3:
                    st.metric("推荐指数", f"{recommendation.预期效果.推荐指数:.2f}")
                    st.metric("情感强度", f"{sentiment_intensity:.2f}")
                
                # 推荐理由和实施建议
                st.subheader("💡 推荐详情")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write("**推荐理由:**")
                    st.info(recommendation.推荐理由)
                    
                    st.write("**实施建议:**")
                    st.info(recommendation.实施建议)
                
                with col2:
                    st.write("**备选方案:**")
                    for i, alt in enumerate(recommendation.备选方案, 1):
                        st.write(f"{i}. {alt}")
                    
                    if include_ab_test:
                        st.write("**A/B测试建议:**")
                        st.info(recommendation.A_B测试建议)
                
                # 预期效果分析
                st.subheader("📊 预期效果分析")
                
                # 创建效果对比图表
                effect_data = {
                    '指标': ['满意度提升', '成本效益比', '历史成功率', '推荐指数'],
                    '数值': [
                        recommendation.预期效果.预期满意度提升,
                        min(recommendation.预期效果.成本效益比, 5),  # 限制显示范围
                        recommendation.预期效果.历史成功率,
                        recommendation.预期效果.推荐指数
                    ]
                }
                
                fig_effect = px.bar(
                    effect_data,
                    x='指标',
                    y='数值',
                    title="补偿方案效果指标对比",
                    color='数值',
                    color_continuous_scale="Viridis"
                )
                st.plotly_chart(fig_effect, use_container_width=True)
                
                # 策略分析结果
                st.subheader("🔍 策略深度分析")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    st.write("**问题诊断:**")
                    st.info(strategy_analysis.问题诊断)
                    
                    st.write("**补偿策略:**")
                    st.info(strategy_analysis.补偿策略)
                
                with col2:
                    if include_roi_analysis:
                        st.metric("预期投资回报率", f"{strategy_analysis.预期ROI:.1%}")
                    
                    if include_risk_analysis:
                        st.write("**风险分析:**")
                        st.warning(strategy_analysis.风险分析)
                    
                    st.write("**长期影响:**")
                    st.info(strategy_analysis.长期影响)
                
                # 历史补偿效果分析
                st.subheader("📈 历史补偿效果分析")
                
                # 模拟历史数据可视化
                historical_data = recommender.effect_data
                problem_data = historical_data[historical_data['problem_type'] == problem_type]
                
                if not problem_data.empty:
                    fig_historical = px.box(
                        problem_data,
                        x='compensation_type',
                        y='satisfaction_improvement',
                        title=f"{problem_type}问题的历史补偿效果分布",
                        labels={'compensation_type': '补偿类型', 'satisfaction_improvement': '满意度提升'}
                    )
                    st.plotly_chart(fig_historical, use_container_width=True)
                
                # A/B测试框架
                if include_ab_test:
                    st.subheader("🔬 A/B测试框架")
                    
                    test_groups = [recommendation.最优补偿方案] + recommendation.备选方案[:2]
                    
                    if st.button("🚀 运行A/B测试模拟"):
                        with st.spinner("正在运行A/B测试模拟..."):
                            ab_result = recommender.run_ab_test(
                                problem_type, sentiment_intensity, test_groups
                            )
                            
                            st.success("A/B测试模拟完成!")
                            
                            col1, col2, col3 = st.columns(3)
                            
                            with col1:
                                st.metric("测试组", ab_result.测试组)
                                st.metric("对照组", ab_result.对照组)
                            
                            with col2:
                                st.metric("满意度提升差异", f"{ab_result.满意度提升差异:.3f}")
                                st.metric("统计显著性", f"p={ab_result.统计显著性:.3f}")
                            
                            with col3:
                                st.write("**测试结论:**")
                                st.info(ab_result.推荐结论)
                
            except Exception as e:
                st.error(f"补偿推荐分析失败: {e}")
    else:
        # 显示示例分析
        st.info("💡 提示：输入客户投诉内容，系统将推荐最优补偿方案")
        
        # 示例投诉
        example_complaints = [
            "航班延误3小时，没有任何解释和补偿",
            "行李被损坏，航空公司处理态度很差",
            "座位非常不舒服，服务人员态度冷漠"
        ]
        
        st.subheader("📝 示例分析")
        for i, complaint in enumerate(example_complaints, 1):
            if st.button(f"示例 {i}: {complaint[:40]}...", key=f"comp_example_{i}"):
                st.session_state.compensation_complaint = complaint
                st.rerun()


def show_competitive_intelligence(df):
    """显示竞争情报与差异化定位系统"""
    st.title("🔍 竞争情报与差异化定位系统")
    
    st.markdown("""
    ### 科学依据：比较分析、竞争优势理论
    
    **系统功能：**
    - 📊 对比不同航空公司在相同问题上的表现差异
    - 🎯 识别自身的相对优势和劣势
    - 💡 发现竞争对手未满足的客户需求（机会空间）
    - 📈 监控竞争对手的服务改进和新举措反响
    
    **数据支撑：**
    - 🏢 跨航空公司（United vs American vs Delta等）的对比分析
    - 📋 问题类型分布差异和情感强度对比
    """)
    
    st.markdown("---")
    
    # 输入区域
    col1, col2 = st.columns([1, 2])
    
    with col1:
        target_airline = st.selectbox(
            "目标航空公司",
            ["united", "american", "delta", "southwest", "us airways"],
            key="target_airline"
        )
        
        competitor_airlines = st.multiselect(
            "竞争对手航空公司",
            ["united", "american", "delta", "southwest", "us airways"],
            default=["american", "delta"],
            key="competitor_airlines"
        )
        
        analysis_depth = st.select_slider(
            "分析深度",
            options=["基础", "标准", "深度"],
            value="标准"
        )
    
    with col2:
        st.subheader("📋 分析选项")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            include_comparison = st.checkbox("包含航空公司对比", value=True)
            include_advantages = st.checkbox("包含竞争优势分析", value=True)
        
        with col2:
            include_opportunities = st.checkbox("包含机会空间发现", value=True)
            include_monitoring = st.checkbox("包含竞争对手监控", value=True)
        
        with col3:
            include_visualization = st.checkbox("包含可视化图表", value=True)
            include_recommendations = st.checkbox("包含战略建议", value=True)
    
    if st.button("🚀 开始竞争情报分析", type="primary") and competitor_airlines:
        with st.spinner("竞争情报系统正在分析中..."):
            try:
                # 初始化竞争情报系统
                intelligence_system = CompetitiveIntelligence()
                
                # 生成竞争洞察报告
                insights_report = intelligence_system.generate_competitive_insights_report(
                    target_airline, competitor_airlines
                )
                
                st.success("🎯 竞争情报分析完成!")
                
                # 航空公司对比分析
                if include_comparison and insights_report['comparisons']:
                    st.subheader("📊 航空公司对比分析")
                    
                    comparisons_df = pd.DataFrame([c.dict() for c in insights_report['comparisons']])
                    
                    # 显示关键指标
                    col1, col2, col3, col4 = st.columns(4)
                    
                    with col1:
                        avg_score = comparisons_df[comparisons_df['航空公司'].str.contains(target_airline)]['满意度得分'].mean()
                        st.metric("目标公司平均得分", f"{avg_score:.1f}")
                    
                    with col2:
                        superior_count = len(comparisons_df[comparisons_df['相对表现'] == '优于'])
                        st.metric("优势领域数量", superior_count)
                    
                    with col3:
                        inferior_count = len(comparisons_df[comparisons_df['相对表现'] == '劣于'])
                        st.metric("劣势领域数量", inferior_count)
                    
                    with col4:
                        equal_count = len(comparisons_df[comparisons_df['相对表现'] == '持平'])
                        st.metric("持平领域数量", equal_count)
                    
                    # 显示详细对比表格
                    st.dataframe(
                        comparisons_df[["航空公司", "问题类型", "满意度得分", "相对表现"]],
                        use_container_width=True
                    )
                
                # 竞争优势分析
                if include_advantages and insights_report['advantages']:
                    st.subheader("💪 竞争优势识别")
                    
                    advantages = insights_report['advantages']
                    
                    for i, advantage in enumerate(advantages, 1):
                        with st.expander(f"优势 {i}: {advantage.优势领域} (相对优势度: {advantage.相对优势度:.1f})"):
                            col1, col2 = st.columns(2)
                            
                            with col1:
                                st.write("**关键指标:**")
                                for metric in advantage.关键指标:
                                    st.write(f"• {metric}")
                            
                            with col2:
                                st.write("**改进建议:**")
                                st.info(advantage.改进建议)
                
                # 机会空间发现
                if include_opportunities and insights_report['opportunities']:
                    st.subheader("💡 机会空间发现")
                    
                    opportunities = insights_report['opportunities']
                    
                    for i, opportunity in enumerate(opportunities, 1):
                        with st.expander(f"机会 {i}: {opportunity.机会领域} (市场规模: {opportunity.潜在市场规模:.1%})"):
                            col1, col2 = st.columns(2)
                            
                            with col1:
                                st.write("**未满足需求:**")
                                st.info(opportunity.未满足需求)
                                
                                st.write("**竞争对手弱点:**")
                                for weakness in opportunity.竞争对手弱点:
                                    st.write(f"• {weakness}")
                            
                            with col2:
                                st.write("**差异化建议:**")
                                st.success(opportunity.差异化建议)
                
                # 竞争对手监控
                if include_monitoring and insights_report['improvements']:
                    st.subheader("📈 竞争对手改进监控")
                    
                    improvements = insights_report['improvements']
                    
                    for competitor, comp_improvements in improvements.items():
                        if comp_improvements:
                            with st.expander(f"{competitor} 的服务改进"):
                                for improvement in comp_improvements:
                                    st.write(f"**问题类型:** {improvement['问题类型']}")
                                    col1, col2, col3 = st.columns(3)
                                    
                                    with col1:
                                        st.metric("改进幅度", f"{improvement['改进幅度']:.1f}")
                                    
                                    with col2:
                                        st.metric("前期表现", f"{improvement['前期表现']:.1f}")
                                    
                                    with col3:
                                        st.metric("后期表现", f"{improvement['后期表现']:.1f}")
                                    
                                    st.write(f"**推断改进措施:** {improvement['改进措施']}")
                                    st.markdown("---")
                
                # 可视化图表
                if include_visualization:
                    st.subheader("📊 可视化分析")
                    
                    charts = create_competitive_analysis_charts(insights_report)
                    
                    if 'comparison_chart' in charts:
                        st.plotly_chart(charts['comparison_chart'], use_container_width=True)
                    
                    if 'advantages_chart' in charts:
                        st.plotly_chart(charts['advantages_chart'], use_container_width=True)
                    
                    if 'opportunities_chart' in charts:
                        st.plotly_chart(charts['opportunities_chart'], use_container_width=True)
                
                # 战略建议
                if include_recommendations:
                    st.subheader("🎯 差异化战略建议")
                    
                    # 生成战略建议
                    strategic_recommendations = {
                        'short_term': "强化现有优势，优化服务流程",
                        'medium_term': "开发差异化服务，抢占市场机会",
                        'long_term': "建立品牌护城河，持续创新",
                        'risks': "关注竞争对手动态，防范市场变化"
                    }
                    
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.write("**短期策略:**")
                        st.info(strategic_recommendations.get('short_term', "强化现有优势，优化服务流程"))
                        
                        st.write("**中期策略:**")
                        st.info(strategic_recommendations.get('medium_term', "开发差异化服务，抢占市场机会"))
                    
                    with col2:
                        st.write("**长期策略:**")
                        st.info(strategic_recommendations.get('long_term', "建立品牌护城河，持续创新"))
                        
                        st.write("**风险预警:**")
                        st.warning(strategic_recommendations.get('risks', "关注竞争对手动态，防范市场变化"))
                
            except Exception as e:
                st.error(f"竞争情报分析失败: {e}")
    else:
        # 显示示例分析
        st.info("💡 提示：选择目标航空公司和竞争对手，系统将进行深度竞争分析")
        
        # 示例分析场景
        example_scenarios = [
            "United vs American & Delta - 全面竞争分析",
            "Southwest vs United & American - 低成本航空竞争",
            "Delta vs American & United - 服务质量对比"
        ]
        
        st.subheader("📝 示例分析场景")
        for i, scenario in enumerate(example_scenarios, 1):
            if st.button(f"场景 {i}: {scenario}", key=f"comp_scenario_{i}"):
                if i == 1:
                    st.session_state.target_airline = "united"
                    st.session_state.competitor_airlines = ["american", "delta"]
                elif i == 2:
                    st.session_state.target_airline = "southwest"
                    st.session_state.competitor_airlines = ["united", "american"]
                else:
                    st.session_state.target_airline = "delta"
                    st.session_state.competitor_airlines = ["american", "united"]
                st.rerun()


if __name__ == "__main__":
    main()