# -*- coding: utf-8 -*-
"""
测试数据库连接
"""
import sys
import pymysql
from dotenv import load_dotenv
import os

# 设置UTF-8编码输出
if sys.platform.startswith('win'):
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

load_dotenv()

def test_connection():
    """测试MySQL连接"""
    print("正在测试数据库连接...")
    print(f"主机: {os.getenv('DB_HOST')}")
    print(f"端口: {os.getenv('DB_PORT')}")
    print(f"用户: {os.getenv('DB_USER')}")
    print(f"数据库: {os.getenv('DB_NAME')}")

    try:
        connection = pymysql.connect(
            host=os.getenv('DB_HOST'),
            port=int(os.getenv('DB_PORT', 3306)),
            user=os.getenv('DB_USER'),
            password=os.getenv('DB_PASSWORD'),
            database=os.getenv('DB_NAME'),
            charset='utf8mb4'
        )

        print("\n✓ 数据库连接成功！")

        # 测试查询
        with connection.cursor() as cursor:
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()
            print(f"✓ MySQL版本: {version[0]}")

            cursor.execute("SHOW TABLES")
            tables = cursor.fetchall()
            if tables:
                print(f"✓ 现有表: {len(tables)} 个")
                for table in tables:
                    print(f"  - {table[0]}")
            else:
                print("  当前数据库为空，可以运行 init_db.py 初始化")

        connection.close()
        return True

    except Exception as e:
        print(f"\n✗ 数据库连接失败: {str(e)}")
        print("\n请检查:")
        print("1. 服务器MySQL是否开放了3306端口")
        print("2. .env文件中的数据库配置是否正确")
        print("3. 数据库用户是否有远程访问权限")
        print("4. 服务器防火墙/安全组是否允许3306端口")
        return False

if __name__ == '__main__':
    test_connection()
