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

"""
数据库迁移命令行工具
用法：
  python migrate.py create "add_user_email" "添加用户邮箱字段"
  python migrate.py status
  python migrate.py migrate [--dry-run] [--target=version]
  python migrate.py rollback version
  python migrate.py validate
"""

import sys
import argparse
import json
from database_migration_manager import DatabaseMigrationManager
from database_config import get_database_config

def create_migration(manager: DatabaseMigrationManager, name: str, description: str = ""):
    """创建新迁移"""
    try:
        filepath = manager.create_migration(name, description)
        print(f"✅ 迁移文件已创建: {filepath}")
        print(f"📝 请编辑文件添加SQL语句")
        return True
    except Exception as e:
        print(f"❌ 创建迁移失败: {e}")
        return False

def show_status(manager: DatabaseMigrationManager):
    """显示迁移状态"""
    try:
        status = manager.get_migration_status()
        
        print("📊 数据库迁移状态")
        print("=" * 50)
        print(f"✅ 已执行: {status['executed_count']}")
        print(f"❌ 失败: {status['failed_count']}")
        print(f"🔄 已回滚: {status['rolled_back_count']}")
        print(f"⏳ 待执行: {status['pending_count']}")
        print()
        
        if status['pending_migrations']:
            print("📋 待执行迁移:")
            for migration in status['pending_migrations']:
                print(f"  • {migration}")
            print()
        
        if status['history']:
            print("📜 迁移历史 (最近10条):")
            for item in status['history'][:10]:
                status_icon = {
                    'SUCCESS': '✅',
                    'FAILED': '❌',
                    'ROLLED_BACK': '🔄'
                }.get(item['status'], '❓')
                
                print(f"  {status_icon} {item['version']} - {item['filename']}")
                print(f"     执行时间: {item['executed_at']}")
                if item['execution_time_ms']:
                    print(f"     耗时: {item['execution_time_ms']}ms")
                if item['error_message']:
                    print(f"     错误: {item['error_message'][:100]}...")
                print()
        
        return True
    except Exception as e:
        print(f"❌ 获取状态失败: {e}")
        return False

def run_migrations(manager: DatabaseMigrationManager, target_version: str = None, dry_run: bool = False):
    """执行迁移"""
    try:
        if dry_run:
            print("🔍 试运行模式 - 不会实际执行迁移")
        
        success = manager.migrate(target_version, dry_run)
        
        if success:
            print("🎉 迁移执行完成!")
        else:
            print("⚠️ 迁移执行过程中出现错误")
            
        return success
    except Exception as e:
        print(f"❌ 执行迁移失败: {e}")
        return False

def rollback_migration(manager: DatabaseMigrationManager, version: str):
    """回滚迁移"""
    try:
        print(f"🔄 准备回滚迁移版本: {version}")
        print("⚠️ 警告: 回滚操作可能导致数据丢失!")
        
        confirm = input("确认继续? (yes/no): ").lower().strip()
        if confirm not in ['yes', 'y']:
            print("❌ 回滚操作已取消")
            return False
        
        success = manager.rollback_migration(version)
        
        if success:
            print("✅ 迁移回滚完成!")
        else:
            print("❌ 迁移回滚失败")
            
        return success
    except Exception as e:
        print(f"❌ 回滚迁移失败: {e}")
        return False

def validate_migrations(manager: DatabaseMigrationManager):
    """验证迁移文件"""
    try:
        success = manager.validate_migrations()
        
        if success:
            print("✅ 所有迁移文件验证通过")
        else:
            print("⚠️ 部分迁移文件验证失败")
            
        return success
    except Exception as e:
        print(f"❌ 验证迁移文件失败: {e}")
        return False

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='数据库迁移管理工具')
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # create 命令
    create_parser = subparsers.add_parser('create', help='创建新迁移')
    create_parser.add_argument('name', help='迁移名称')
    create_parser.add_argument('description', nargs='?', default='', help='迁移描述')
    
    # status 命令
    subparsers.add_parser('status', help='显示迁移状态')
    
    # migrate 命令
    migrate_parser = subparsers.add_parser('migrate', help='执行迁移')
    migrate_parser.add_argument('--dry-run', action='store_true', help='试运行模式')
    migrate_parser.add_argument('--target', help='目标版本')
    
    # rollback 命令
    rollback_parser = subparsers.add_parser('rollback', help='回滚迁移')
    rollback_parser.add_argument('version', help='要回滚的版本号')
    
    # validate 命令
    subparsers.add_parser('validate', help='验证迁移文件')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return 1
    
    try:
        # 获取数据库配置
        db_config = get_database_config()
        manager = DatabaseMigrationManager(db_config)
        
        # 执行对应命令
        if args.command == 'create':
            success = create_migration(manager, args.name, args.description)
        elif args.command == 'status':
            success = show_status(manager)
        elif args.command == 'migrate':
            success = run_migrations(manager, args.target, args.dry_run)
        elif args.command == 'rollback':
            success = rollback_migration(manager, args.version)
        elif args.command == 'validate':
            success = validate_migrations(manager)
        else:
            print(f"❌ 未知命令: {args.command}")
            return 1
        
        return 0 if success else 1
        
    except Exception as e:
        print(f"❌ 执行失败: {e}")
        return 1

if __name__ == '__main__':
    sys.exit(main())
