#!/usr/bin/env python3
"""用当前环境变量连接数据库，依次调用 list_connections、list_databases、list_tables、analyze_sql、execute_sql(SELECT 1)。"""
import os
import sys

# 确保能 import 到 mysql_mcp
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from mysql_mcp.config import load_connection_map, load_safety_config
from mysql_mcp.client import connect, list_databases, list_tables, get_connection_config, execute_select
from mysql_mcp.sql_analysis import analyze_one


def main():
    default_conn, conn_map, default_name = load_connection_map()
    safety = load_safety_config()

    print("=== list_connections 等效 ===")
    print(f"默认 profile: {default_name}")
    for k, c in sorted(conn_map.items()):
        print(f"  {k}: {c.host}:{c.port} user={c.user} database={c.database or '(未指定)'}")

    config = get_connection_config(None, default_conn, conn_map)
    print(f"\n使用连接: {config.host}:{config.port} database={config.database}")

    with connect(config, safety) as conn:
        dbs = list_databases(conn, getattr(config, "databases", None))
        print(f"\n=== list_databases === 共 {len(dbs)} 个库")
        for db in (dbs or [])[:20]:
            print(f"  {db}")
        if len(dbs or []) > 20:
            print(f"  ... 等共 {len(dbs)} 个")

        db_name = config.database or (dbs[0] if dbs else None)
        if not db_name:
            print("\n跳过 list_tables（无默认库且未指定）")
        else:
            tables = list_tables(conn, db_name)
            print(f"\n=== list_tables({db_name!r}) === 共 {len(tables)} 张表")
            for t in (tables or [])[:10]:
                print(f"  {t.get('name', t)}")
            if len(tables or []) > 10:
                print(f"  ... 等共 {len(tables)} 张")

    a = analyze_one("SELECT 1")
    print(f"\n=== analyze_sql('SELECT 1') === type={a.stype} need_confirm={a.need_confirm} message={a.message}")

    with connect(config, safety) as conn:
        rows, truncated = execute_select(conn, "SELECT 1 AS n", max_rows=safety.max_select_rows)
        print(f"\n=== execute_sql('SELECT 1') === rows={len(rows)} truncated={truncated}")
        if rows:
            print(f"  结果: {rows[0]}")

    print("\n测试通过。")


if __name__ == "__main__":
    main()
