#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
数据库迁移脚本
用于自动检测模型变更并应用到数据库

用法:
    python scripts/run_migration.py [--verbose]

示例:
    # 执行自动迁移
    python scripts/run_migration.py
    
    # 显示详细日志
    python scripts/run_migration.py --verbose
"""

import argparse
import os
import sys
import logging
from pathlib import Path

# 添加项目根目录到系统路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# 导入项目日志模块
from utils.logger import setup_logger
from utils.db_migration import run_migration, DBMigration

# 设置日志
setup_logger()
logger = logging.getLogger('migration')

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="执行数据库自动迁移")
    parser.add_argument("--verbose", "-v", action="store_true", help="显示详细日志")
    
    args = parser.parse_args()
    
    # 设置日志级别
    log_level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(
        level=log_level,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    
    logger.info("开始执行数据库自动迁移...")
    
    # 运行迁移
    success = run_migration()
    
    if success:
        logger.info("数据库迁移成功完成！")
    else:
        logger.error("数据库迁移失败！")
    
    # 根据迁移结果设置退出码
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main() 