"""
配置迁移 - JSON 配置文件 → MySQL
"""
import logging

from app.config_store import get_config_store, CONFIG_FILES, DEFAULT_CONFIGS

logger = logging.getLogger(__name__)

CONFIG_KEYS = ["symbols", "ai"]


def migrate_configs_to_mysql():
    """
    将 JSON 配置文件迁移到 MySQL。

    Returns:
        bool: 迁移是否成功
    """
    store = get_config_store()

    if not store.storage_manager.check_mysql():
        logger.warning("MySQL 不可用，跳过配置迁移")
        return True

    if store.session_maker is None:
        logger.warning("MySQL session 未初始化，跳过配置迁移")
        return True

    migrated_count = 0
    skipped_count = 0

    for key in CONFIG_KEYS:
        try:
            if store._config_exists_in_mysql(key):
                logger.info(f"MySQL 配置 [{key}] 已存在，跳过迁移")
                skipped_count += 1
                continue

            value = store._load_json_from_file(key)
            if value is None:
                value = DEFAULT_CONFIGS.get(key, {})
                logger.info(f"JSON 配置 [{key}] 不存在或损坏，使用默认值迁移")
            store._save_to_mysql(key, value)
            migrated_count += 1
            logger.info(f"配置 [{key}] 已从 JSON 迁移到 MySQL")
        except Exception as e:
            logger.error(f"迁移配置 [{key}] 失败: {e}")
            return False

    logger.info(f"配置迁移完成: 迁移 {migrated_count} 项，跳过 {skipped_count} 项")
    return True
