"""
初始化配置到数据库（从config.py迁移）
"""
import sys
from pathlib import Path

# 添加项目根目录和trading_system目录
project_root = Path(__file__).parent.parent
trading_system_path = project_root / 'trading_system'

# 确保trading_system在路径中
if str(trading_system_path) not in sys.path:
    sys.path.insert(0, str(trading_system_path))

# 确保backend在路径中（用于导入database模块）
backend_path = Path(__file__).parent
if str(backend_path) not in sys.path:
    sys.path.insert(0, str(backend_path))

# 导入数据库模型
from database.models import TradingConfig

# 导入交易系统配置（现在在trading_system目录下）
try:
    import config
except ImportError:
    # 如果直接导入失败，尝试从trading_system导入
    sys.path.insert(0, str(trading_system_path))
    import config

def init_configs():
    """将config.py中的配置初始化到数据库"""
    print("开始初始化配置到数据库...")
    
    # API配置
    TradingConfig.set('BINANCE_API_KEY', config.BINANCE_API_KEY, 'string', 'api', '币安API密钥')
    TradingConfig.set('BINANCE_API_SECRET', config.BINANCE_API_SECRET, 'string', 'api', '币安API密钥')
    TradingConfig.set('USE_TESTNET', config.USE_TESTNET, 'boolean', 'api', '是否使用测试网')
    
    # 交易配置
    trading_config = config.TRADING_CONFIG
    for key, value in trading_config.items():
        # 确定类型
        if isinstance(value, bool):
            config_type = 'boolean'
        elif isinstance(value, (int, float)):
            config_type = 'number'
        elif isinstance(value, (list, dict)):
            config_type = 'json'
        else:
            config_type = 'string'
        
        # 确定分类
        if key == 'TOP_N_SYMBOLS' or key == 'MAX_SCAN_SYMBOLS' or key == 'POSITION_SYNC_INTERVAL':
            category = 'scan'
        elif 'POSITION' in key and 'SYNC' not in key:
            category = 'position'
        elif 'RISK' in key or 'STOP' in key or 'PROFIT' in key:
            category = 'risk'
        elif 'SCAN' in key or 'INTERVAL' in key or 'VOLUME' in key:
            category = 'scan'
        else:
            category = 'strategy'
        
        TradingConfig.set(key, value, config_type, category, f'{key}配置')
    
    print("配置初始化完成！")
    print(f"共初始化 {len(trading_config) + 3} 个配置项")

if __name__ == '__main__':
    try:
        init_configs()
    except Exception as e:
        print(f"初始化失败: {e}")
        import traceback
        traceback.print_exc()
