# -*- coding: utf-8 -*-
"""
数据导出脚本
导出现有数据到SQL文件
"""
import subprocess
import os
from datetime import datetime

def export_database():
    """导出数据库到SQL文件"""
    # 从.env读取数据库配置
    from dotenv import load_dotenv
    load_dotenv()

    db_host = os.getenv('DB_HOST', 'localhost')
    db_port = os.getenv('DB_PORT', '3306')
    db_user = os.getenv('DB_USER')
    db_password = os.getenv('DB_PASSWORD')
    db_name = os.getenv('DB_NAME')

    # 生成备份文件名
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_file = f'backup_{db_name}_{timestamp}.sql'

    # mysqldump命令
    cmd = [
        'mysqldump',
        '-h', db_host,
        '-P', db_port,
        '-u', db_user,
        f'-p{db_password}',
        '--single-transaction',
        '--routines',
        '--triggers',
        db_name
    ]

    print(f"正在导出数据库 {db_name} ...")

    try:
        with open(backup_file, 'w', encoding='utf-8') as f:
            subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, check=True)

        file_size = os.path.getsize(backup_file) / 1024  # KB
        print(f"✓ 数据库导出成功！")
        print(f"  文件: {backup_file}")
        print(f"  大小: {file_size:.2f} KB")
        print(f"\n请将此文件上传到服务器进行恢复")

    except subprocess.CalledProcessError as e:
        print(f"✗ 导出失败: {e.stderr.decode()}")
    except FileNotFoundError:
        print("✗ 错误: 找不到 mysqldump 命令")
        print("  请确保MySQL客户端工具已安装并在PATH中")

if __name__ == '__main__':
    export_database()
