"""
TradingAgents 图结构创建模块
============================

提供统一的图创建接口，支持混合数据源模式

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

import os
from typing import Dict, Any, List, Optional
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode

from tradingagents.agents.state import AgentState
from tradingagents.default_config import DEFAULT_CONFIG


def create_graph(
    config: Optional[Dict[str, Any]] = None,
    selected_analysts: List[str] = ["market", "social", "news", "fundamentals"],
    debug: bool = False
) -> Any:
    """
    创建TradingAgents分析图。
    注意: 此版本强制使用与混合模式兼容的简化图，以避免状态不兼容错误。
    """
    final_config = config or DEFAULT_CONFIG.copy()
    print("通知: 正在创建与混合模式兼容的简化分析图。")
    return create_simplified_graph(final_config)


def create_simplified_graph(config: Dict[str, Any]) -> StateGraph:
    """
    创建简化版本的分析图
    
    @param {Dict[str, Any]} config - 配置字典
    @returns {StateGraph} 简化的分析图
    """
    
    # 初始化LLM
    llm = ChatOpenAI(
        model=config.get("quick_think_llm", "gpt-4.1-2025-04-14"),
        temperature=0.1
    )
    
    # 创建状态图
    workflow = StateGraph(AgentState)
    
    # 添加节点
    workflow.add_node("analyzer", create_analyzer_node(llm))
    workflow.add_node("decision_maker", create_decision_node(llm))
    
    # 设置入口点
    workflow.set_entry_point("analyzer")
    
    # 添加边
    workflow.add_edge("analyzer", "decision_maker")
    workflow.add_edge("decision_maker", END)
    
    # 编译图
    graph = workflow.compile()
    
    return graph


def create_analyzer_node(llm: ChatOpenAI):
    """
    创建分析节点
    
    @param {ChatOpenAI} llm - 语言模型实例
    @returns {function} 分析节点函数
    """
    
    def analyzer(state: AgentState) -> AgentState:
        """分析股票数据"""
        
        # 构建分析提示
        prompt = f"""
        作为专业的股票分析师，请分析以下股票数据：
        
        股票代码: {state.get('ticker', 'N/A')}
        公司名称: {state.get('company_name', 'N/A')}
        当前价格: {state.get('current_price', 'N/A')}
        市值: {state.get('market_cap', 'N/A')}
        PE比率: {state.get('pe_ratio', 'N/A')}
        行业: {state.get('sector', 'N/A')}
        
        技术指标:
        - RSI: {state.get('rsi', 'N/A')}
        - SMA 20: {state.get('sma_20', 'N/A')}
        - SMA 50: {state.get('sma_50', 'N/A')}
        
        最近新闻: {len(state.get('recent_news', []))} 条
        
        请提供详细的技术分析和基本面分析。
        """
        
        try:
            response = llm.invoke(prompt)
            analysis = response.content
            
            # 更新状态
            state['technical_analysis'] = analysis
            state['analysis_completed'] = True
            
        except Exception as e:
            state['analysis_error'] = str(e)
            state['technical_analysis'] = f"分析失败: {e}"
        
        return state
    
    return analyzer


def create_decision_node(llm: ChatOpenAI):
    """
    创建决策节点
    
    @param {ChatOpenAI} llm - 语言模型实例
    @returns {function} 决策节点函数
    """
    
    def decision_maker(state: AgentState) -> AgentState:
        """做出投资决策"""
        
        analysis = state.get('technical_analysis', '')
        
        prompt = f"""
        基于以下分析，请做出投资决策：
        
        {analysis}
        
        请提供：
        1. 投资决策 (BUY/SELL/HOLD)
        2. 置信度 (0-1之间的数值)
        3. 决策理由
        
        请以JSON格式回复：
        {{
            "decision": "BUY/SELL/HOLD",
            "confidence": 0.75,
            "reasoning": "详细理由..."
        }}
        """
        
        try:
            response = llm.invoke(prompt)
            decision_text = response.content
            
            # 简单解析决策（实际应用中可以使用更复杂的解析）
            if "BUY" in decision_text.upper():
                decision = "BUY"
                confidence = 0.7
            elif "SELL" in decision_text.upper():
                decision = "SELL"
                confidence = 0.7
            else:
                decision = "HOLD"
                confidence = 0.5
            
            # 更新状态
            state['final_decision'] = decision
            state['confidence'] = confidence
            state['reasoning'] = decision_text
            state['decision_completed'] = True
            
        except Exception as e:
            state['decision_error'] = str(e)
            state['final_decision'] = 'HOLD'
            state['confidence'] = 0.5
            state['reasoning'] = f"决策失败: {e}"
        
        return state
    
    return decision_maker


def create_hybrid_graph(
    config: Optional[Dict[str, Any]] = None,
    enable_free_sources: bool = True
) -> Any:
    """
    创建混合数据源图
    
    @param {Dict[str, Any]} config - 配置字典
    @param {bool} enable_free_sources - 是否启用免费数据源
    @returns {Any} 混合图实例
    """
    
    final_config = config or DEFAULT_CONFIG.copy()
    
    # 添加混合模式标志
    final_config['hybrid_mode'] = True
    final_config['enable_free_sources'] = enable_free_sources
    
    return create_graph(final_config)


# 向后兼容的别名
def setup_graph(*args, **kwargs):
    """向后兼容的图设置函数"""
    return create_graph(*args, **kwargs)


# 导出主要函数
__all__ = [
    'create_graph',
    'create_simplified_graph', 
    'create_hybrid_graph',
    'setup_graph'
]