"""
TradingAgents 状态管理模块
=========================

定义智能体状态和数据结构

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

from typing import Dict, Any, List, Optional, Union
from dataclasses import dataclass, field
from datetime import datetime


@dataclass
class AgentState:
    """
    智能体状态类
    
    @description 存储分析过程中的所有状态信息
    """
    
    # 基本股票信息
    ticker: str = ""
    company_name: str = ""
    sector: str = ""
    industry: str = ""
    trade_date: str = ""
    company_of_interest: str = ""
    
    # 兼容性字段 - 支持完整图结构
    investment_debate_state: Optional[Dict[str, Any]] = None
    risk_debate_state: Optional[Dict[str, Any]] = None
    market_report: str = ""
    sentiment_report: str = ""
    news_report: str = ""
    fundamentals_report: str = ""
    investment_plan: str = ""
    trader_investment_plan: str = ""
    final_trade_decision: str = ""
    
    # 价格数据
    current_price: Optional[float] = None
    price_change_24h: Optional[float] = None
    price_change_52w: Optional[float] = None
    volume: Optional[int] = None
    avg_volume: Optional[int] = None
    
    # 市场数据
    market_cap: Optional[float] = None
    shares_outstanding: Optional[int] = None
    float_shares: Optional[int] = None
    
    # 财务指标
    revenue: Optional[float] = None
    net_income: Optional[float] = None
    total_assets: Optional[float] = None
    total_debt: Optional[float] = None
    cash_and_equivalents: Optional[float] = None
    
    # 估值指标
    pe_ratio: Optional[float] = None
    pb_ratio: Optional[float] = None
    ps_ratio: Optional[float] = None
    peg_ratio: Optional[float] = None
    ev_ebitda: Optional[float] = None
    
    # 技术指标
    rsi: Optional[float] = None
    sma_20: Optional[float] = None
    sma_50: Optional[float] = None
    sma_200: Optional[float] = None
    ema_12: Optional[float] = None
    ema_26: Optional[float] = None
    macd: Optional[float] = None
    bollinger_upper: Optional[float] = None
    bollinger_lower: Optional[float] = None
    
    # 分析师数据
    analyst_rating: Optional[str] = None
    target_price: Optional[float] = None
    num_analysts: Optional[int] = None
    
    # 新闻和情绪
    recent_news: List[Dict[str, Any]] = field(default_factory=list)
    sentiment_score: Optional[float] = None
    social_mentions: Optional[int] = None
    
    # 分析结果
    technical_analysis: str = ""
    fundamental_analysis: str = ""
    news_analysis: str = ""
    sentiment_analysis: str = ""
    
    # 决策信息
    final_decision: str = "HOLD"
    confidence: float = 0.5
    reasoning: str = ""
    
    # 元数据
    data_sources: List[str] = field(default_factory=list)
    analysis_timestamp: str = ""
    config_name: str = ""
    using_free_sources: bool = True
    
    # 状态标志
    analysis_completed: bool = False
    decision_completed: bool = False
    
    # 错误信息
    analysis_error: Optional[str] = None
    decision_error: Optional[str] = None
    data_errors: List[str] = field(default_factory=list)
    
    # 性能指标
    response_time: Optional[float] = None
    api_calls_used: int = 0
    estimated_cost: Optional[float] = None
    
    def __post_init__(self):
        """初始化后处理"""
        if not self.analysis_timestamp:
            self.analysis_timestamp = datetime.now().isoformat()
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'ticker': self.ticker,
            'company_name': self.company_name,
            'sector': self.sector,
            'current_price': self.current_price,
            'market_cap': self.market_cap,
            'pe_ratio': self.pe_ratio,
            'final_decision': self.final_decision,
            'confidence': self.confidence,
            'reasoning': self.reasoning,
            'data_sources': self.data_sources,
            'analysis_timestamp': self.analysis_timestamp,
            'config_name': self.config_name,
            'using_free_sources': self.using_free_sources,
            'analysis_completed': self.analysis_completed,
            'decision_completed': self.decision_completed,
            'response_time': self.response_time,
            'estimated_cost': self.estimated_cost
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """字典式访问方法"""
        return getattr(self, key, default)
    
    def __getitem__(self, key: str) -> Any:
        """支持字典式访问"""
        return getattr(self, key)
    
    def __setitem__(self, key: str, value: Any):
        """支持字典式设置"""
        setattr(self, key, value)
    
    def __contains__(self, key: str) -> bool:
        """支持in操作符"""
        return hasattr(self, key)
    
    def update(self, data: Dict[str, Any]):
        """批量更新状态"""
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)
    
    def add_error(self, error: str):
        """添加错误信息"""
        self.data_errors.append(error)
    
    def has_errors(self) -> bool:
        """检查是否有错误"""
        return bool(self.analysis_error or self.decision_error or self.data_errors)
    
    def get_summary(self) -> Dict[str, Any]:
        """获取状态摘要"""
        return {
            'ticker': self.ticker,
            'decision': self.final_decision,
            'confidence': self.confidence,
            'completed': self.analysis_completed and self.decision_completed,
            'has_errors': self.has_errors(),
            'data_sources': len(self.data_sources),
            'timestamp': self.analysis_timestamp
        }


# 向后兼容的类型别名
class InvestDebateState(dict):
    """投资辩论状态（向后兼容）"""
    pass


class RiskDebateState(dict):
    """风险辩论状态（向后兼容）"""
    pass


# 导出主要类
__all__ = [
    'AgentState',
    'InvestDebateState', 
    'RiskDebateState'
]