"""智能版 Streamlit 演示应用 - 推文情感分析

移除手动选择航空公司功能，实现智能识别和上下文感知分析。
"""

import os
import sys
import time
import asyncio
import streamlit as st
from datetime import datetime

# Ensure project root is in path
sys.path.append(os.getcwd())

# 首先加载环境变量
from dotenv import load_dotenv
load_dotenv()

# 然后导入配置和其他模块
from src.config import Config
from src.deepseek_agent_optimized import analyze_tweet_sync
from src.tweet_agent_enhanced import analyze_tweet as analyze_tweet_enhanced
from src.airline_detector import extract_airline_context

# 页面配置
st.set_page_config(
    page_title="智能航空推文分析", 
    page_icon="✈️", 
    layout="wide",
    initial_sidebar_state="expanded"
)

# 自定义CSS样式
st.markdown("""
<style>
    .main-header {
        text-align: center;
        padding: 1rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        margin-bottom: 1rem;
    }
    .sentiment-card {
        padding: 1rem;
        border-radius: 10px;
        margin: 0.5rem 0;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .negative { background-color: #ff6b6b; color: white; }
    .neutral { background-color: #ffd93d; color: #333; }
    .positive { background-color: #6bcb77; color: white; }
    .priority-high { background-color: #ff4757; color: white; }
    .priority-medium { background-color: #ffa502; color: white; }
    .priority-low { background-color: #2ed573; color: white; }
    .context-info {
        background-color: #f8f9fa;
        padding: 0.5rem;
        border-radius: 5px;
        border-left: 4px solid #6c757d;
        margin: 0.5rem 0;
    }
</style>
""", unsafe_allow_html=True)

# 页面标题
st.markdown("""
<div class="main-header">
    <h1>✈️ 智能航空推文分析系统</h1>
    <p>基于上下文感知的实时情感分析与智能处置方案</p>
</div>
""", unsafe_allow_html=True)

# 侧边栏配置
with st.sidebar:
    st.header("⚙️ 系统配置")
    
    # API 状态显示
    api_valid, api_message = Config.validate_config_with_message()
    api_status = "✅ 可用" if api_valid else "❌ 不可用"
    
    st.metric("DeepSeek API 状态", api_status)
    
    if not api_valid:
        st.error(f"⚠️ {api_message}")
    
    st.markdown("---")
    
    # 分析模式选择
    st.markdown("### 🔧 分析模式")
    
    # 根据API状态动态调整可用模式
    available_modes = ["🤖 智能模式 (推荐)", "⚙️ 传统模型"]
    if api_valid:
        available_modes.insert(1, "🧠 DeepSeek API")
    
    analysis_mode = st.radio(
        "选择分析引擎",
        available_modes,
        help="智能模式会自动选择最优分析方式"
    )
    
    # 模式描述
    mode_descriptions = {
        "🤖 智能模式 (推荐)": "自动选择最优分析方式，平衡准确性和速度",
        "🧠 DeepSeek API": "使用大语言模型进行深度语义分析",
        "⚙️ 传统模型": "使用预训练的机器学习模型"
    }
    
    if analysis_mode == "🧠 DeepSeek API" and not api_valid:
        st.warning("⚠️ DeepSeek API 当前不可用，将自动切换到传统模型")
    else:
        st.info(mode_descriptions[analysis_mode])
    
    st.markdown("---")
    
    # 功能选择
    st.markdown("### 📋 功能菜单")
    app_mode = st.radio(
        "选择功能",
        ["📝 智能分析", "📊 批量处理", "📈 分析统计"]
    )

# 初始化会话状态
if "analysis_history" not in st.session_state:
    st.session_state.analysis_history = []

if "performance_stats" not in st.session_state:
    st.session_state.performance_stats = {
        "total_analyses": 0,
        "avg_processing_time": 0,
        "sentiment_distribution": {"negative": 0, "neutral": 0, "positive": 0}
    }

# 工具函数
def get_sentiment_emoji(sentiment: str) -> str:
    """获取情感对应的表情符号"""
    emoji_map = {
        "negative": "😠",
        "neutral": "😐", 
        "positive": "😊",
    }
    return emoji_map.get(sentiment, "❓")

def get_priority_emoji(priority: str) -> str:
    """获取优先级对应的表情符号"""
    emoji_map = {
        "high": "🔴",
        "medium": "🟡",
        "low": "🟢",
    }
    return emoji_map.get(priority, "⚪")

def get_urgency_emoji(urgency: str) -> str:
    """获取紧急程度对应的表情符号"""
    emoji_map = {
        "immediate": "🚨",
        "soon": "⏰", 
        "normal": "📅",
    }
    return emoji_map.get(urgency, "📌")

# 主要功能界面
if app_mode == "📝 智能分析":
    st.markdown("### 📝 智能推文分析")
    
    # 输入区域
    with st.container():
        tweet_text = st.text_area(
            "✍️ 推文内容",
            placeholder="例如：@United 航班延误了3小时，服务态度很差，非常失望...",
            height=120,
            help="请输入要分析的航空推文内容，系统会自动识别航空公司"
        )
    
    # 分析按钮
    col1, col2, col3 = st.columns([1, 2, 1])
    with col2:
        analyze_btn = st.button(
            "🚀 开始智能分析", 
            type="primary", 
            use_container_width=True,
            disabled=not tweet_text.strip()
        )
    
    if analyze_btn and tweet_text:
        # 显示分析进度
        progress_bar = st.progress(0)
        status_text = st.empty()
        
        try:
            # 分析进度模拟
            for i in range(4):
                progress = (i + 1) * 25
                progress_bar.progress(progress)
                
                if i == 0:
                    status_text.text("🔍 正在识别上下文...")
                elif i == 1:
                    status_text.text("😊 正在分析情感倾向...")
                elif i == 2:
                    status_text.text("💭 正在生成解释...")
                else:
                    status_text.text("🚀 正在制定处置方案...")
                
                time.sleep(0.3)
            
            # 自动识别航空公司上下文（不显示给用户）
            airline_context = extract_airline_context(tweet_text)
            suggested_airline = airline_context.get("primary_airline", "通用航空公司")
            
            # 2. 执行分析
            start_time = time.time()
            
            try:
                if analysis_mode == "🧠 DeepSeek API":
                    if api_valid:
                        result = analyze_tweet_sync(tweet_text, suggested_airline)
                    else:
                        st.warning("DeepSeek API 不可用，自动切换到传统模型")
                        result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                elif analysis_mode == "⚙️ 传统模型":
                    result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                else:  # 智能模式
                    if api_valid:
                        result = analyze_tweet_sync(tweet_text, suggested_airline)
                    else:
                        result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                
                processing_time = time.time() - start_time
                
            except Exception as analysis_error:
                # 分析失败时的优雅降级
                processing_time = time.time() - start_time
                st.error(f"分析过程中出现错误: {str(analysis_error)}")
                
                # 尝试使用传统模型作为备选
                try:
                    status_text.text("🔄 尝试使用传统模型...")
                    result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                    st.info("✅ 已成功使用传统模型完成分析")
                except Exception as fallback_error:
                    # 如果传统模型也失败，抛出错误
                    raise Exception(f"所有分析模式都失败: {str(fallback_error)}")
            
            # 完成进度
            progress_bar.progress(100)
            status_text.text("✅ 分析完成!")
            
            # 显示结果
            st.success(f"分析完成！耗时: {processing_time:.2f}秒 | 上下文: {suggested_airline}")
            
            # 情感分析结果
            st.markdown("### 😊 情感分析结果")
            
            # 统一处理不同的结果对象
            if hasattr(result, 'sentiment_analysis'):
                sentiment_result = result.sentiment_analysis
                disposal_plan = result.disposal_plan
            else:
                sentiment_result = result.classification
                disposal_plan = result.disposal_plan
            
            sentiment = sentiment_result.sentiment
            confidence = sentiment_result.confidence
            intensity = getattr(sentiment_result, 'intensity', 'moderate')
            
            # 情感卡片
            sentiment_color = {
                "negative": "negative", 
                "neutral": "neutral", 
                "positive": "positive"
            }[sentiment]
            
            st.markdown(f"""
            <div class="sentiment-card {sentiment_color}">
                <h2>{get_sentiment_emoji(sentiment)} {sentiment.upper()}</h2>
                <p><strong>置信度:</strong> {confidence:.1%} | <strong>情感强度:</strong> {intensity}</p>
            </div>
            """, unsafe_allow_html=True)
            
            # 分析详情
            col1, col2 = st.columns(2)
            
            with col1:
                st.markdown("#### 🔍 关键因素")
                factors = getattr(sentiment_result, 'key_factors', [])
                if factors:
                    factors = factors[:Config.MAX_DISPLAY_FACTORS]
                    for factor in factors:
                        st.markdown(f"- {factor}")
                else:
                    st.info("未识别到明显的关键因素")
            
            with col2:
                st.markdown("#### 💭 推理过程")
                reasoning = getattr(sentiment_result, 'reasoning', '基于模型分析得出结果')
                st.info(reasoning)
            
            # 处置方案
            st.markdown("### 🚀 处置方案")
            
            priority = disposal_plan.priority
            urgency = getattr(disposal_plan, 'urgency_level', 'normal')
            
            st.markdown(f"""
            <div class="priority-{priority}" style="padding: 1rem; border-radius: 10px; color: white;">
                <h3>{get_priority_emoji(priority)} 优先级: {priority.upper()}</h3>
                <p>{get_urgency_emoji(urgency)} 紧急程度: {urgency} | 📋 行动类型: {disposal_plan.action_type}</p>
            </div>
            """, unsafe_allow_html=True)
            
            if disposal_plan.suggested_response:
                st.markdown("#### 💬 建议回复")
                with st.expander("查看建议回复"):
                    st.success(disposal_plan.suggested_response)
            
            st.markdown("#### 📋 后续行动")
            actions = disposal_plan.follow_up_actions[:Config.MAX_DISPLAY_ACTIONS]
            for i, action in enumerate(actions, 1):
                st.markdown(f"{i}. {action}")
            
            st.markdown("#### 📝 制定理由")
            reasoning = getattr(disposal_plan, 'reasoning', '基于情感分析结果制定')
            st.info(reasoning)
            
            # 记录分析历史
            analysis_record = {
                "timestamp": datetime.now(),
                "tweet": tweet_text[:100] + "..." if len(tweet_text) > 100 else tweet_text,
                "airline": suggested_airline,
                "sentiment": sentiment,
                "confidence": confidence,
                "processing_time": processing_time,
                "mode": analysis_mode,
                "airline_context": airline_context
            }
            st.session_state.analysis_history.insert(0, analysis_record)
            
            # 更新统计信息
            st.session_state.performance_stats["total_analyses"] += 1
            st.session_state.performance_stats["sentiment_distribution"][sentiment] += 1
            
        except Exception as e:
            st.error(f"❌ 分析失败: {str(e)}")
            st.info("💡 建议检查网络连接或尝试切换分析模式")

elif app_mode == "📊 批量处理":
    st.markdown("### 📊 批量推文处理")
    
    # 批量处理模式选择
    batch_mode = st.radio(
        "选择批量处理方式",
        ["📁 上传CSV文件", "✍️ 手动输入多条数据"],
        horizontal=True
    )
    
    if batch_mode == "📁 上传CSV文件":
        st.markdown("#### 📁 CSV文件上传")
        
        uploaded_file = st.file_uploader(
            "上传CSV文件", 
            type=['csv'],
            help="请上传包含推文数据的CSV文件，文件应包含'tweet_text'列"
        )
        
        if uploaded_file is not None:
            try:
                import pandas as pd
                
                # 读取CSV文件
                df = pd.read_csv(uploaded_file)
                
                # 检查必要的列
                if 'tweet_text' not in df.columns:
                    st.error("❌ CSV文件必须包含'tweet_text'列")
                else:
                    st.success(f"✅ 成功读取文件，共 {len(df)} 条推文")
                    
                    # 显示数据预览
                    with st.expander("📋 数据预览", expanded=True):
                        st.dataframe(df.head(), use_container_width=True)
                    
                    # 批量分析按钮
                    if st.button("🚀 开始批量分析", type="primary"):
                        # 批量分析逻辑
                        batch_results = []
                        progress_bar = st.progress(0)
                        
                        for i, row in df.iterrows():
                            tweet_text = str(row['tweet_text'])
                            
                            # 更新进度
                            progress = int((i + 1) / len(df) * 100)
                            progress_bar.progress(progress)
                            
                            try:
                                # 执行单条分析
                                airline_context = extract_airline_context(tweet_text)
                                suggested_airline = airline_context.get("primary_airline", "通用航空公司")
                                
                                # 根据分析模式选择分析函数
                                if analysis_mode == "🧠 DeepSeek API" and api_valid:
                                    result = analyze_tweet_sync(tweet_text, suggested_airline)
                                else:
                                    result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                                
                                # 统一处理结果
                                if hasattr(result, 'sentiment_analysis'):
                                    sentiment_result = result.sentiment_analysis
                                    disposal_plan = result.disposal_plan
                                else:
                                    sentiment_result = result.classification
                                    disposal_plan = result.disposal_plan
                                
                                batch_results.append({
                                    '序号': i + 1,
                                    '推文': tweet_text[:100] + "..." if len(tweet_text) > 100 else tweet_text,
                                    '航空公司': suggested_airline,
                                    '情感': sentiment_result.sentiment,
                                    '置信度': sentiment_result.confidence,
                                    '优先级': disposal_plan.priority,
                                    '行动类型': disposal_plan.action_type
                                })
                                
                            except Exception as e:
                                batch_results.append({
                                    '序号': i + 1,
                                    '推文': tweet_text[:100] + "..." if len(tweet_text) > 100 else tweet_text,
                                    '航空公司': "分析失败",
                                    '情感': "错误",
                                    '置信度': 0.0,
                                    '优先级': "未知",
                                    '行动类型': "检查错误"
                                })
                        
                        # 显示批量分析结果
                        st.markdown("### 📊 批量分析结果")
                        
                        # 转换为DataFrame显示
                        results_df = pd.DataFrame(batch_results)
                        st.dataframe(results_df, use_container_width=True)
                        
                        # 统计信息
                        st.markdown("#### 📈 分析统计")
                        
                        col1, col2, col3, col4 = st.columns(4)
                        
                        with col1:
                            st.metric("总推文数", len(df))
                        with col2:
                            success_count = len([r for r in batch_results if r['情感'] != "错误"])
                            st.metric("成功分析", success_count)
                        with col3:
                            error_count = len([r for r in batch_results if r['情感'] == "错误"])
                            st.metric("分析失败", error_count)
                        with col4:
                            success_rate = (success_count / len(df)) * 100 if len(df) > 0 else 0
                            st.metric("成功率", f"{success_rate:.1f}%")
                        
                        # 情感分布
                        sentiment_counts = results_df['情感'].value_counts()
                        
                        if not sentiment_counts.empty:
                            st.markdown("#### 😊 情感分布")
                            
                            sentiment_cols = st.columns(len(sentiment_counts))
                            for idx, (sentiment, count) in enumerate(sentiment_counts.items()):
                                with sentiment_cols[idx % len(sentiment_cols)]:
                                    st.metric(f"{get_sentiment_emoji(sentiment)} {sentiment}", count)
                        
                        # 导出功能
                        st.markdown("#### 💾 结果导出")
                        
                        csv_data = results_df.to_csv(index=False).encode('utf-8')
                        st.download_button(
                            label="� 下载CSV结果",
                            data=csv_data,
                            file_name=f"批量分析结果_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                            mime="text/csv"
                        )
                        
            except Exception as e:
                st.error(f"❌ 文件处理错误: {str(e)}")
    
    else:  # 手动输入多条数据
        st.markdown("#### ✍️ 手动输入多条数据")
        
        # 多行文本输入
        multi_tweets = st.text_area(
            "输入多条推文（每行一条）",
            placeholder="例如：\n@United 航班延误了3小时，服务态度很差\n@Delta 服务非常专业，体验很好\n机场安检排队时间太长",
            height=200,
            help="每行输入一条推文，系统将逐条进行分析"
        )
        
        if st.button("🚀 开始批量分析", type="primary") and multi_tweets.strip():
            # 分割推文
            tweets = [tweet.strip() for tweet in multi_tweets.split('\n') if tweet.strip()]
            
            if tweets:
                st.success(f"✅ 识别到 {len(tweets)} 条推文")
                
                # 批量分析逻辑
                batch_results = []
                progress_bar = st.progress(0)
                
                for i, tweet_text in enumerate(tweets):
                    # 更新进度
                    progress = int((i + 1) / len(tweets) * 100)
                    progress_bar.progress(progress)
                    
                    try:
                        # 执行单条分析
                        airline_context = extract_airline_context(tweet_text)
                        suggested_airline = airline_context.get("primary_airline", "通用航空公司")
                        
                        # 根据分析模式选择分析函数
                        if analysis_mode == "🧠 DeepSeek API" and api_valid:
                            result = analyze_tweet_sync(tweet_text, suggested_airline)
                        else:
                            result = analyze_tweet_enhanced(tweet_text, suggested_airline, "traditional")
                        
                        # 统一处理结果
                        if hasattr(result, 'sentiment_analysis'):
                            sentiment_result = result.sentiment_analysis
                            disposal_plan = result.disposal_plan
                        else:
                            sentiment_result = result.classification
                            disposal_plan = result.disposal_plan
                        
                        batch_results.append({
                            '序号': i + 1,
                            '推文': tweet_text[:100] + "..." if len(tweet_text) > 100 else tweet_text,
                            '航空公司': suggested_airline,
                            '情感': sentiment_result.sentiment,
                            '置信度': sentiment_result.confidence,
                            '优先级': disposal_plan.priority,
                            '行动类型': disposal_plan.action_type
                        })
                        
                    except Exception as e:
                        batch_results.append({
                            '序号': i + 1,
                            '推文': tweet_text[:100] + "..." if len(tweet_text) > 100 else tweet_text,
                            '航空公司': "分析失败",
                            '情感': "错误",
                            '置信度': 0.0,
                            '优先级': "未知",
                            '行动类型': "检查错误"
                        })
                
                # 显示批量分析结果
                st.markdown("### 📊 批量分析结果")
                
                # 转换为DataFrame显示
                import pandas as pd
                results_df = pd.DataFrame(batch_results)
                st.dataframe(results_df, use_container_width=True)
                
                # 统计信息
                st.markdown("#### 📈 分析统计")
                
                col1, col2, col3, col4 = st.columns(4)
                
                with col1:
                    st.metric("总推文数", len(tweets))
                with col2:
                    success_count = len([r for r in batch_results if r['情感'] != "错误"])
                    st.metric("成功分析", success_count)
                with col3:
                    error_count = len([r for r in batch_results if r['情感'] == "错误"])
                    st.metric("分析失败", error_count)
                with col4:
                    success_rate = (success_count / len(tweets)) * 100 if len(tweets) > 0 else 0
                    st.metric("成功率", f"{success_rate:.1f}%")
                
                # 情感分布
                sentiment_counts = results_df['情感'].value_counts()
                
                if not sentiment_counts.empty:
                    st.markdown("#### 😊 情感分布")
                    
                    sentiment_cols = st.columns(len(sentiment_counts))
                    for idx, (sentiment, count) in enumerate(sentiment_counts.items()):
                        with sentiment_cols[idx % len(sentiment_cols)]:
                            st.metric(f"{get_sentiment_emoji(sentiment)} {sentiment}", count)
                
                # 导出功能
                st.markdown("#### 💾 结果导出")
                
                csv_data = results_df.to_csv(index=False).encode('utf-8')
                st.download_button(
                    label="📥 下载CSV结果",
                    data=csv_data,
                    file_name=f"批量分析结果_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                    mime="text/csv"
                )

elif app_mode == "📈 分析统计":
    st.markdown("### 📈 分析统计")
    
    if not st.session_state.analysis_history:
        st.info("📊 暂无分析数据，请先进行智能分析")
    else:
        # 统计信息
        total_analyses = st.session_state.performance_stats["total_analyses"]
        sentiment_dist = st.session_state.performance_stats["sentiment_distribution"]
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("总分析次数", total_analyses)
        with col2:
            negative_pct = (sentiment_dist["negative"] / total_analyses * 100) if total_analyses > 0 else 0
            st.metric("负面情感比例", f"{negative_pct:.1f}%")
        with col3:
            avg_time = sum([r["processing_time"] for r in st.session_state.analysis_history]) / total_analyses
            st.metric("平均处理时间", f"{avg_time:.2f}s")
        
        # 航空公司统计
        airline_stats = {}
        for record in st.session_state.analysis_history:
            airline = record["airline"]
            if airline not in airline_stats:
                airline_stats[airline] = 0
            airline_stats[airline] += 1
        
        if airline_stats:
            st.markdown("#### ✈️ 航空公司分布")
            for airline, count in sorted(airline_stats.items(), key=lambda x: x[1], reverse=True)[:5]:
                st.write(f"- **{airline}**: {count} 次分析")

# 页脚信息
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; font-size: 0.9em;">
    <p>🚀 智能航空推文分析系统 v3.0 | 基于上下文感知的实时情感分析</p>
    <p>💡 技术支持: 机器学习课程设计项目</p>
</div>
""", unsafe_allow_html=True)