"""
元数据属性迁移脚本：将meta_data节点的type属性改为data_type属性
运行方式：python migrate_meta_data_type.py
"""

import logging
import sys
import time
from app.services.neo4j_driver import neo4j_driver

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger("meta_data_migration")

def migrate_type_to_data_type():
    """
    将meta_data节点的type属性迁移到data_type属性
    """
    try:
        with neo4j_driver.get_session() as session:
            # 查询拥有type属性的meta_data节点数量
            count_query = """
            MATCH (n:meta_data)
            WHERE EXISTS(n.type)
            RETURN COUNT(n) as count
            """
            count_result = session.run(count_query)
            node_count = count_result.single()["count"]
            
            if node_count == 0:
                logger.info("没有找到带有type属性的meta_data节点，无需迁移")
                return
                
            logger.info(f"找到 {node_count} 个需要迁移的meta_data节点")
            
            # 执行迁移：复制type属性到data_type，然后删除type属性
            migrate_query = """
            MATCH (n:meta_data)
            WHERE EXISTS(n.type)
            SET n.data_type = n.type
            REMOVE n.type
            RETURN COUNT(n) as migrated_count
            """
            
            migrate_result = session.run(migrate_query)
            migrated_count = migrate_result.single()["migrated_count"]
            
            logger.info(f"成功迁移 {migrated_count} 个meta_data节点的type属性到data_type属性")
            
            # 验证迁移结果
            verify_query = """
            MATCH (n:meta_data)
            WHERE EXISTS(n.type)
            RETURN COUNT(n) as remaining_count
            """
            verify_result = session.run(verify_query)
            remaining_count = verify_result.single()["remaining_count"]
            
            if remaining_count > 0:
                logger.warning(f"仍有 {remaining_count} 个meta_data节点保留了type属性")
            else:
                logger.info("所有meta_data节点的type属性已成功迁移到data_type属性")
                
    except Exception as e:
        logger.error(f"迁移过程中发生错误: {str(e)}")
        raise

if __name__ == "__main__":
    try:
        logger.info("开始迁移meta_data节点的type属性到data_type属性...")
        start_time = time.time()
        
        migrate_type_to_data_type()
        
        end_time = time.time()
        execution_time = end_time - start_time
        logger.info(f"迁移完成，耗时: {execution_time:.2f} 秒")
        
    except Exception as e:
        logger.error(f"迁移失败: {str(e)}")
        sys.exit(1) 