"""
标签关联分析服务类
整合分析器和数据库操作，提供完整的分析+存储功能
"""

import logging
import sys
import os
from typing import Dict, Any, Optional, List

# 处理相对导入和绝对导入
try:
    from .tag_relation_analyzer import TagRelationAnalyzer
    from .tag_relation_database import TagRelationDatabase
except ImportError:
    # 如果相对导入失败，使用绝对导入
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from stock_tag_analysis.tag_relation_analyzer import TagRelationAnalyzer
    from stock_tag_analysis.tag_relation_database import TagRelationDatabase

# 设置日志记录
logger = logging.getLogger(__name__)


class TagRelationService:
    """标签关联分析服务类"""
    
    def __init__(self, model_type: str = "ds3_2", enable_web_search: bool = True, collection_name: Optional[str] = None):
        """初始化服务
        
        Args:
            model_type: 大模型类型，默认为 ds3_2
            enable_web_search: 是否启用联网搜索，默认True
            collection_name: MongoDB集合名称，如果不指定则使用默认集合名
        """
        # 初始化分析器
        self.analyzer = TagRelationAnalyzer(
            model_type=model_type,
            enable_web_search=enable_web_search
        )
        
        # 初始化数据库
        self.database = TagRelationDatabase(collection_name=collection_name)
        
        logger.info("TagRelationService 初始化完成")
    
    def analyze_and_save(
        self,
        stock_code: str,
        stock_name: str,
        tag_name: str,
        temperature: float = 0.7,
        max_tokens: int = 4096,
        save_to_db: bool = True
    ) -> Dict[str, Any]:
        """分析个股与标签的关联性并保存到数据库
        
        Args:
            stock_code: 股票代码（如：300750.SZ）
            stock_name: 股票名称（如：宁德时代）
            tag_name: 标签名称（如：医药、新能源、金融科技等）
            temperature: 大模型温度参数，默认0.7
            max_tokens: 最大token数，默认4096
            save_to_db: 是否保存到数据库，默认True
            
        Returns:
            Dict[str, Any]: 分析结果，包含所有分析字段和保存状态
        """
        try:
            # 执行分析
            logger.info(f"开始分析 {stock_name}({stock_code}) 与标签 {tag_name} 的关联性")
            analysis_result = self.analyzer.analyze_tag_relation(
                stock_code=stock_code,
                stock_name=stock_name,
                tag_name=tag_name,
                temperature=temperature,
                max_tokens=max_tokens
            )
            
            # 保存到数据库
            if save_to_db and analysis_result.get('success'):
                save_success = self.database.save_analysis_result(analysis_result)
                analysis_result['saved_to_db'] = save_success
                if save_success:
                    logger.info(f"分析结果已保存到数据库: {stock_code} - {tag_name}")
                else:
                    logger.warning(f"分析结果保存失败: {stock_code} - {tag_name}")
            else:
                analysis_result['saved_to_db'] = False
                if not save_to_db:
                    logger.info(f"跳过数据库保存: {stock_code} - {tag_name}")
            
            return analysis_result
            
        except Exception as e:
            logger.error(f"分析并保存过程中出错: {str(e)}", exc_info=True)
            return {
                "success": False,
                "stock_code": stock_code,
                "stock_name": stock_name,
                "tag_name": tag_name,
                "error": str(e),
                "saved_to_db": False
            }
    
    def batch_analyze_and_save(
        self,
        stock_list: List[Dict[str, str]],
        tag_name: str,
        temperature: float = 0.7,
        max_tokens: int = 4096,
        save_to_db: bool = True
    ) -> List[Dict[str, Any]]:
        """批量分析多只股票与标签的关联性并保存到数据库
        
        Args:
            stock_list: 股票列表，每个元素包含 stock_code 和 stock_name
            tag_name: 标签名称
            temperature: 大模型温度参数
            max_tokens: 最大token数
            save_to_db: 是否保存到数据库，默认True
            
        Returns:
            List[Dict[str, Any]]: 分析结果列表
        """
        results = []
        total = len(stock_list)
        
        for idx, stock in enumerate(stock_list, 1):
            stock_code = stock.get("stock_code")
            stock_name = stock.get("stock_name")
            
            if not stock_code or not stock_name:
                logger.warning(f"跳过无效股票信息: {stock}")
                continue
            
            logger.info(f"处理进度: {idx}/{total} - {stock_name}({stock_code})")
            
            result = self.analyze_and_save(
                stock_code=stock_code,
                stock_name=stock_name,
                tag_name=tag_name,
                temperature=temperature,
                max_tokens=max_tokens,
                save_to_db=save_to_db
            )
            results.append(result)
        
        # 统计结果
        success_count = sum(1 for r in results if r.get('success'))
        saved_count = sum(1 for r in results if r.get('saved_to_db'))
        logger.info(f"批量分析完成 - 总数: {len(results)}, 成功: {success_count}, 已保存: {saved_count}")
        
        return results
    
    def get_analysis_result(self, stock_code: str, tag_name: str) -> Optional[Dict[str, Any]]:
        """从数据库获取分析结果
        
        Args:
            stock_code: 股票代码
            tag_name: 标签名称
            
        Returns:
            Optional[Dict[str, Any]]: 分析结果，如果不存在返回None
        """
        return self.database.get_analysis_result(stock_code, tag_name)
    
    def get_stock_analyses(self, stock_code: str) -> list:
        """获取指定股票的所有标签分析结果
        
        Args:
            stock_code: 股票代码
            
        Returns:
            list: 分析结果列表
        """
        return self.database.get_stock_analyses(stock_code)
    
    def get_tag_analyses(self, tag_name: str) -> list:
        """获取指定标签的所有股票分析结果
        
        Args:
            tag_name: 标签名称
            
        Returns:
            list: 分析结果列表
        """
        return self.database.get_tag_analyses(tag_name)
    
    def close(self):
        """关闭数据库连接"""
        self.database.close_connection()


if __name__ == "__main__":
    # 设置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    # 测试示例
    service = TagRelationService()
    
    # 测试：分析宁德时代与医药标签的关联性并保存
    result = service.analyze_and_save(
        stock_code="000547.SZ",
        stock_name="航天发展",
        tag_name="商业航天"
    )
    
    print("\n" + "="*50)
    print("分析结果：")
    print("="*50)
    print(f"成功: {result.get('success')}")
    print(f"已保存: {result.get('saved_to_db')}")
    print(f"关联度评分: {result.get('relation_score')}")
    print(f"结论: {result.get('conclusion')}")
    
    # 关闭连接
    service.close()

