# -*- coding: utf-8 -*-
"""Database connectivity helpers."""

from .shared import Any, Dict


def test_mysql_connection(
    db_host: str,
    db_port: int,
    db_user: str,
    db_pass: str,
    timeout: int = 5,
) -> Dict[str, Any]:
    """Open a real MySQL connection and run a lightweight probe query."""
    try:
        import pymysql
    except ImportError as exc:
        raise ImportError("需要安装 pymysql: pip install pymysql") from exc

    conn = None
    cursor = None
    try:
        conn = pymysql.connect(
            host=str(db_host).strip(),
            port=int(db_port),
            user=str(db_user).strip(),
            password=db_pass or "",
            charset="utf8mb4",
            connect_timeout=timeout,
            read_timeout=timeout,
            write_timeout=timeout,
            autocommit=True,
        )
        conn.ping(reconnect=False)
        cursor = conn.cursor()
        cursor.execute("SELECT 1, VERSION(), CURRENT_USER()")
        row = cursor.fetchone() or ()
        return {
            "ok": True,
            "server_version": str(row[1]) if len(row) > 1 and row[1] is not None else "",
            "current_user": str(row[2]) if len(row) > 2 and row[2] is not None else "",
        }
    finally:
        if cursor is not None:
            cursor.close()
        if conn is not None:
            conn.close()
