#!/usr/bin/env python3
"""
TradingAgents Streamlit Web界面
==============================

提供用户友好的Web界面进行股票分析：
- 🎨 现代化界面设计
- 📊 交互式图表展示
- ⚡ 实时分析进度
- 💰 成本监控
- 📈 历史记录管理

@author TradingAgents团队
@version MVP-1.0
@since 2024-12
"""

import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import json
import time
import sys
from pathlib import Path
import logging
from typing import Dict, Any, List

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

# 导入核心模块
try:
    from main_hybrid import HybridTradingEngine
    from tradingagents.hybrid_config import list_available_configs, HYBRID_CONFIGURATIONS
except ImportError as e:
    st.error(f"导入错误: {e}")
    st.stop()

# 页面配置
st.set_page_config(
    page_title="TradingAgents - AI股票分析",
    page_icon="📈",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 自定义CSS样式
st.markdown("""
<style>
    .main > div {
        padding-top: 2rem;
    }
    .stAlert > div {
        padding-top: 1rem;
    }
    .metric-card {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        padding: 1rem;
        border-radius: 10px;
        color: white;
        margin: 0.5rem 0;
    }
    .success-metric {
        background: linear-gradient(90deg, #56ab2f 0%, #a8e6cf 100%);
        padding: 1rem;
        border-radius: 10px;
        color: white;
    }
    .warning-metric {
        background: linear-gradient(90deg, #f12711 0%, #f5af19 100%);
        padding: 1rem;
        border-radius: 10px;
        color: white;
    }
    .sidebar .sidebar-content {
        background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
    }
</style>
""", unsafe_allow_html=True)

# 初始化会话状态
if 'analysis_history' not in st.session_state:
    st.session_state.analysis_history = []
if 'total_cost' not in st.session_state:
    st.session_state.total_cost = 0.0
if 'engine' not in st.session_state:
    st.session_state.engine = None

def initialize_engine(config_name: str):
    """初始化交易引擎"""
    try:
        if st.session_state.engine is None or st.session_state.get('current_config') != config_name:
            with st.spinner("🚀 初始化交易引擎..."):
                st.session_state.engine = HybridTradingEngine(config_name)
                st.session_state.current_config = config_name
                st.success(f"✅ 引擎已初始化 - 配置: {config_name}")
        return st.session_state.engine
    except Exception as e:
        st.error(f"❌ 引擎初始化失败: {e}")
        return None

def create_price_chart(symbol: str, analysis_result: Dict[str, Any]) -> go.Figure:
    """创建价格图表"""
    try:
        # 模拟价格数据（实际应用中应该从分析结果中获取）
        dates = pd.date_range(end=datetime.now(), periods=30, freq='D')
        base_price = analysis_result.get('full_analysis', {}).get('current_price', 100)
        
        # 生成模拟的价格走势
        import numpy as np
        np.random.seed(42)
        prices = base_price + np.cumsum(np.random.randn(30) * 2)
        
        fig = go.Figure()
        
        # 添加价格线
        fig.add_trace(go.Scatter(
            x=dates,
            y=prices,
            mode='lines+markers',
            name=f'{symbol} 价格',
            line=dict(color='#1f77b4', width=2),
            marker=dict(size=4)
        ))
        
        # 添加决策标记
        decision = analysis_result.get('decision', 'HOLD')
        decision_color = {
            'BUY': 'green',
            'SELL': 'red',
            'HOLD': 'orange'
        }.get(decision, 'gray')
        
        fig.add_annotation(
            x=dates[-1],
            y=prices[-1],
            text=f"AI决策: {decision}",
            showarrow=True,
            arrowhead=2,
            arrowcolor=decision_color,
            bgcolor=decision_color,
            bordercolor="white",
            font=dict(color="white")
        )
        
        fig.update_layout(
            title=f"{symbol} 价格走势与AI决策",
            xaxis_title="日期",
            yaxis_title="价格 ($)",
            template="plotly_white",
            height=400
        )
        
        return fig
    except Exception as e:
        st.error(f"图表创建失败: {e}")
        return go.Figure()

def create_metrics_dashboard(analysis_result: Dict[str, Any]):
    """创建指标仪表板"""
    try:
        # 提取关键指标
        decision = analysis_result.get('decision', 'UNKNOWN')
        confidence = analysis_result.get('confidence', 0) * 100
        cost = analysis_result.get('estimated_cost', 0)
        response_time = analysis_result.get('response_time', 0)
        data_sources = analysis_result.get('data_sources', [])
        
        # 创建4列布局
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric(
                label="🎯 AI决策",
                value=decision,
                delta=f"置信度: {confidence:.1f}%"
            )
        
        with col2:
            st.metric(
                label="💰 分析成本",
                value=f"${cost:.4f}",
                delta=f"累计: ${st.session_state.total_cost:.4f}"
            )
        
        with col3:
            st.metric(
                label="⚡ 响应时间",
                value=f"{response_time:.2f}s",
                delta="免费数据源" if len(data_sources) > 0 else "无数据"
            )
        
        with col4:
            st.metric(
                label="📊 数据源",
                value=str(len(data_sources)),
                delta=", ".join(data_sources[:2]) + ("..." if len(data_sources) > 2 else "")
            )
    
    except Exception as e:
        st.error(f"指标仪表板创建失败: {e}")

def create_analysis_summary(analysis_result: Dict[str, Any]):
    """创建分析摘要"""
    try:
        with st.expander("📋 详细分析摘要", expanded=True):
            col1, col2 = st.columns(2)
            
            with col1:
                st.subheader("🎯 核心决策")
                decision = analysis_result.get('decision', 'UNKNOWN')
                confidence = analysis_result.get('confidence', 0)
                
                # 决策颜色编码
                decision_color = {
                    'BUY': '🟢',
                    'SELL': '🔴', 
                    'HOLD': '🟡'
                }.get(decision, '⚪')
                
                st.markdown(f"""
                **决策**: {decision_color} **{decision}**
                
                **置信度**: {confidence * 100:.1f}%
                
                **风险评级**: {'高' if confidence < 0.6 else '中' if confidence < 0.8 else '低'}
                """)
            
            with col2:
                st.subheader("📊 数据质量")
                data_sources = analysis_result.get('data_sources', [])
                config_name = analysis_result.get('config_name', 'unknown')
                
                st.markdown(f"""
                **配置方案**: {config_name}
                
                **数据源数量**: {len(data_sources)}
                
                **主要来源**: {', '.join(data_sources[:3])}
                
                **免费源占比**: 100%
                """)
            
            # 分析推理
            reasoning = analysis_result.get('reasoning', '')
            if reasoning:
                st.subheader("🧠 AI分析推理")
                st.text_area("分析推理", reasoning, height=200)
    
    except Exception as e:
        st.error(f"分析摘要创建失败: {e}")

def create_cost_tracking_chart():
    """创建成本追踪图表"""
    try:
        if len(st.session_state.analysis_history) > 1:
            df = pd.DataFrame(st.session_state.analysis_history)
            df['cumulative_cost'] = df['cost'].cumsum()
            
            fig = px.line(
                df, 
                x='timestamp', 
                y='cumulative_cost',
                title="📈 累计分析成本趋势",
                labels={'cumulative_cost': '累计成本 ($)', 'timestamp': '时间'}
            )
            
            fig.update_layout(
                template="plotly_white",
                height=300
            )
            
            return fig
    except Exception as e:
        st.error(f"成本追踪图表创建失败: {e}")
    
    return None

def main():
    """主界面"""
    # 页面标题
    st.title("🚀 TradingAgents - AI股票分析平台")
    st.markdown("*基于混合数据源的智能股票分析系统*")
    
    # 侧边栏配置
    with st.sidebar:
        st.header("⚙️ 配置设置")
        
        # 配置选择
        config_options = list_available_configs()
        selected_config = st.selectbox(
            "选择配置方案",
            config_options,
            index=config_options.index('balanced') if 'balanced' in config_options else 0,
            help="不同配置方案有不同的成本和数据质量平衡"
        )
        
        # 显示配置详情
        if selected_config in HYBRID_CONFIGURATIONS:
            config = HYBRID_CONFIGURATIONS[selected_config]
            with st.expander("配置详情"):
                st.write(f"**免费基本面**: {'✅' if config.use_free_fundamentals else '❌'}")
                st.write(f"**免费新闻**: {'✅' if config.use_free_news else '❌'}")
                st.write(f"**付费Fallback**: {'✅' if config.finnhub_enable_fallback else '❌'}")
                st.write(f"**缓存时间**: {config.cache_ttl_hours}小时")
                st.write(f"**日API限制**: {config.av_daily_limit}次")
        
        # 分析选项
        st.header("🎛️ 分析选项")
        enable_reasoning = st.checkbox("启用深度推理", value=True, help="更详细的分析但速度较慢")
        
        # 成本监控
        st.header("💰 成本监控")
        st.metric("累计成本", f"${st.session_state.total_cost:.4f}")
        st.metric("分析次数", len(st.session_state.analysis_history))
        
        if st.session_state.analysis_history:
            avg_cost = st.session_state.total_cost / len(st.session_state.analysis_history)
            st.metric("平均成本", f"${avg_cost:.4f}")
    
    # 主界面内容
    # 股票输入区域
    col1, col2 = st.columns([3, 1])
    
    with col1:
        symbol_input = st.text_input(
            "🏷️ 输入股票代码",
            placeholder="例如: AAPL, NVDA, TSLA",
            help="输入单个股票代码进行分析"
        ).upper()
    
    with col2:
        st.write("")  # 空行对齐
        analyze_button = st.button("🔍 开始分析", type="primary", use_container_width=True)
    
    # 批量分析区域
    with st.expander("📊 批量分析"):
        batch_symbols = st.text_area(
            "批量股票代码",
            placeholder="输入多个股票代码，用逗号分隔\n例如: AAPL,NVDA,TSLA,MSFT",
            height=100
        )
        
        col1, col2 = st.columns(2)
        with col1:
            batch_analyze_button = st.button("🔄 批量分析", use_container_width=True)
        with col2:
            if st.button("🗑️ 清空历史", use_container_width=True):
                st.session_state.analysis_history = []
                st.session_state.total_cost = 0.0
                st.success("历史记录已清空")
                st.experimental_rerun()
    
    # 执行单个分析
    if analyze_button and symbol_input:
        engine = initialize_engine(selected_config)
        if engine:
            with st.spinner(f"🔍 正在分析 {symbol_input}..."):
                try:
                    result = engine.analyze_stock(symbol_input, enable_reasoning)
                    
                    if result.get('status') == 'success':
                        # 更新会话状态
                        st.session_state.analysis_history.append({
                            'symbol': symbol_input,
                            'timestamp': datetime.now(),
                            'decision': result.get('decision'),
                            'confidence': result.get('confidence', 0),
                            'cost': result.get('estimated_cost', 0)
                        })
                        st.session_state.total_cost += result.get('estimated_cost', 0)
                        
                        # 显示结果
                        st.success(f"✅ {symbol_input} 分析完成！")
                        
                        # 指标仪表板
                        create_metrics_dashboard(result)
                        
                        # 价格图表
                        fig = create_price_chart(symbol_input, result)
                        st.plotly_chart(fig, use_container_width=True)
                        
                        # 分析摘要
                        create_analysis_summary(result)
                        
                    else:
                        st.error(f"❌ 分析失败: {result.get('error', '未知错误')}")
                        
                except Exception as e:
                    st.error(f"❌ 分析过程中发生错误: {e}")
    
    # 执行批量分析
    if batch_analyze_button and batch_symbols:
        symbols = [s.strip().upper() for s in batch_symbols.split(',') if s.strip()]
        if symbols:
            engine = initialize_engine(selected_config)
            if engine:
                # 创建进度条
                progress_bar = st.progress(0)
                status_text = st.empty()
                
                try:
                    results = {}
                    total_cost = 0
                    
                    for i, symbol in enumerate(symbols):
                        status_text.text(f"🔍 分析 {symbol} ({i+1}/{len(symbols)})")
                        progress_bar.progress((i + 1) / len(symbols))
                        
                        result = engine.analyze_stock(symbol, enable_reasoning)
                        results[symbol] = result
                        
                        if result.get('status') == 'success':
                            cost = result.get('estimated_cost', 0)
                            total_cost += cost
                            
                            # 更新历史记录
                            st.session_state.analysis_history.append({
                                'symbol': symbol,
                                'timestamp': datetime.now(),
                                'decision': result.get('decision'),
                                'confidence': result.get('confidence', 0),
                                'cost': cost
                            })
                    
                    st.session_state.total_cost += total_cost
                    
                    # 显示批量结果
                    status_text.text("✅ 批量分析完成！")
                    
                    # 结果摘要
                    successful = sum(1 for r in results.values() if r.get('status') == 'success')
                    failed = len(symbols) - successful
                    
                    col1, col2, col3, col4 = st.columns(4)
                    with col1:
                        st.metric("总计", len(symbols))
                    with col2:
                        st.metric("成功", successful)
                    with col3:
                        st.metric("失败", failed)
                    with col4:
                        st.metric("总成本", f"${total_cost:.4f}")
                    
                    # 结果表格
                    result_data = []
                    for symbol, result in results.items():
                        if result.get('status') == 'success':
                            result_data.append({
                                '股票代码': symbol,
                                'AI决策': result.get('decision', 'UNKNOWN'),
                                '置信度': f"{result.get('confidence', 0) * 100:.1f}%",
                                '成本': f"${result.get('estimated_cost', 0):.4f}",
                                '响应时间': f"{result.get('response_time', 0):.2f}s"
                            })
                        else:
                            result_data.append({
                                '股票代码': symbol,
                                'AI决策': '失败',
                                '置信度': 'N/A',
                                '成本': '$0.0000',
                                '响应时间': 'N/A'
                            })
                    
                    if result_data:
                        df = pd.DataFrame(result_data)
                        st.dataframe(df, use_container_width=True)
                
                except Exception as e:
                    st.error(f"❌ 批量分析失败: {e}")
    
    # 历史记录展示
    if st.session_state.analysis_history:
        st.header("📊 分析历史")
        
        # 成本追踪图表
        cost_chart = create_cost_tracking_chart()
        if cost_chart:
            st.plotly_chart(cost_chart, use_container_width=True)
        
        # 历史记录表格
        df_history = pd.DataFrame(st.session_state.analysis_history)
        df_history['置信度'] = (df_history['confidence'] * 100).round(1).astype(str) + '%'
        df_history['成本'] = '$' + df_history['cost'].round(4).astype(str)
        df_history['时间'] = df_history['timestamp'].dt.strftime('%H:%M:%S')
        
        display_df = df_history[['symbol', 'decision', '置信度', '成本', '时间']].copy()
        display_df.columns = ['股票代码', 'AI决策', '置信度', '成本', '时间']
        
        st.dataframe(display_df, use_container_width=True)
    
    # 页脚信息
    st.markdown("---")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.markdown("**🚀 TradingAgents MVP**")
        st.markdown("智能股票分析平台")
    
    with col2:
        st.markdown("**💰 成本优化**")
        st.markdown("节省85%数据成本")
    
    with col3:
        st.markdown("**🔄 实时分析**")
        st.markdown("AI驱动决策支持")

if __name__ == "__main__":
    main() 