# 适配器工厂类
import json
import os
from qihuo_analyzer.data.api_adapters.base_adapter import BaseDataAdapter
from qihuo_analyzer.data.api_adapters.tqsdk_adapter import TqSdkAdapter
from qihuo_analyzer.data.api_adapters.rqdata_adapter import RqDataAdapter


class DataAdapterFactory:
    """数据适配器工厂类
    
    根据配置创建相应的数据适配器实例。
    """
    
    @staticmethod
    def _load_config():
        """加载配置文件
        
        Returns:
            dict: 配置信息
        """
        config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))), 'config.json')
        print(config_path)
        if os.path.exists(config_path):
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                return config
            except Exception as e:
                print(f"加载配置文件失败：{e}")
                return {}
        else:
            print(f"配置文件不存在：{config_path}")
            return {}
    
    @staticmethod
    def create_adapter(adapter_type: str = None) -> BaseDataAdapter:
        """创建数据适配器
        
        Args:
            adapter_type: 适配器类型，可选值：'tqsdk', 'rqdata'。如果为None，则从配置文件获取。
            
        Returns:
            BaseDataAdapter: 数据适配器实例
        """
        # 加载配置文件
        config = DataAdapterFactory._load_config()
        
        # 获取数据源配置
        data_source_config = config.get('dataSource', {})
        
        # 如果没有指定适配器类型，从配置文件获取
        if adapter_type is None:
            adapter_type = data_source_config.get('defaultDataSource', 'tqsdk').lower()
        
        # 根据类型创建适配器
        if adapter_type == 'tqsdk':
            print("创建TQSDK数据适配器")
            # 获取TQSDK配置
            tqsdk_config = data_source_config.get('tqsdk', {})
            username = tqsdk_config.get('username', '')
            password = tqsdk_config.get('password', '')
            return TqSdkAdapter(username=username, password=password)
        elif adapter_type == 'rqdata':
            print("创建RQData数据适配器")
            # 获取RQData配置
            rqdata_config = data_source_config.get('rqdata', {})
            username = rqdata_config.get('username', '')
            password = rqdata_config.get('password', '')
            return RqDataAdapter(username=username, password=password)
        else:
            # 默认使用TQSDK适配器
            print(f"未知的适配器类型：{adapter_type}，使用默认的TQSDK适配器")
            # 获取TQSDK配置
            tqsdk_config = data_source_config.get('tqsdk', {})
            username = tqsdk_config.get('username', '')
            password = tqsdk_config.get('password', '')
            return TqSdkAdapter(username=username, password=password)