"""Cerebro Database connection singleton with async wrapper."""

import asyncio
import sys

from cerebro_mcp.auth import connect_db, login as auth_login

_db = None
_connection_method = None


def get_db():
    """Lazy singleton. Uses auth fallback chain."""
    global _db, _connection_method
    if _db is None:
        _db, _connection_method = connect_db()
        print(f"Cerebro MCP: подключено через {_connection_method}", file=sys.stderr)
    return _db


def do_login(host: str, username: str, password: str) -> str:
    """Explicit login. Resets singleton."""
    global _db, _connection_method
    _db = auth_login(host, username, password)
    _connection_method = f"login (user={username})"
    print(f"Cerebro MCP: подключено через {_connection_method}", file=sys.stderr)
    return f"Подключено к {host} как {username}"


async def execute(method_name, *args, **kwargs):
    """asyncio.to_thread() wrapper with auto-reconnect on failure."""
    def _call():
        db = get_db()
        return getattr(db, method_name)(*args, **kwargs)

    try:
        return await asyncio.to_thread(_call)
    except Exception:
        global _db
        _db = None
        return await asyncio.to_thread(_call)
