#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库备份脚本
在容器内执行数据库备份
"""

import os
import sys
import subprocess
from pathlib import Path
from datetime import datetime

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

def run_command(command, description):
    """执行命令并处理错误"""
    print(f"🔄 {description}...")
    try:
        # 使用bash -c来确保命令正确执行
        result = subprocess.run(
            f"bash -c '{command}'",
            shell=True,
            check=True,
            capture_output=True,
            text=True,
            cwd=project_root
        )
        print(f"✅ {description} 成功")
        if result.stdout:
            print(f"输出: {result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败")
        print(f"错误: {e.stderr}")
        return False

def backup_database():
    """备份数据库"""
    print("🚀 数据库备份工具启动")
    print(f"📍 项目根目录: {project_root}")

    # 确保备份目录存在
    backup_dir = project_root / "database" / "backups"
    backup_dir.mkdir(exist_ok=True)

    # 生成带时间戳的备份文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_file = backup_dir / f"auto_backup_{timestamp}.sql"

    print(f"📁 备份文件: {backup_file}")
    print(f"🔄 备份数据库到 {backup_file.name}...")

    try:
        # 分步执行备份（使用已验证的方法）
        # 1. 创建配置文件
        config_cmd = "echo '[client]\nhost=mysql\nuser=callback_user\npassword=dev_password_123\nssl=0' > /tmp/backup.cnf"
        subprocess.run(config_cmd, shell=True, check=True)

        # 2. 执行备份
        backup_cmd = f"mysqldump --defaults-file=/tmp/backup.cnf --single-transaction --routines --triggers callback_system > {backup_file}"
        result = subprocess.run(backup_cmd, shell=True, capture_output=True, text=True)

        # 3. 清理配置文件
        subprocess.run("rm -f /tmp/backup.cnf", shell=True)

        # 检查备份文件大小
        if backup_file.exists() and backup_file.stat().st_size > 0:
            print("✅ 备份数据库成功")
            print(f"📊 备份文件大小: {backup_file.stat().st_size} 字节")
            print("🎉 数据库备份完成")
            return True
        else:
            print(f"❌ 备份数据库失败")
            if result.stderr:
                print(f"错误: {result.stderr}")
            return False

    except Exception as e:
        print(f"❌ 备份过程中发生异常: {e}")
        return False

if __name__ == '__main__':
    success = backup_database()
    sys.exit(0 if success else 1)
