from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase

from app.core.config import settings

_client: AsyncIOMotorClient | None = None


def get_client() -> AsyncIOMotorClient:
    global _client
    if _client is None:
        _client = AsyncIOMotorClient(settings.MONGO_URI)
    return _client


def reset_client() -> None:
    global _client
    if _client is not None:
        _client.close()
    _client = None


def get_db() -> AsyncIOMotorDatabase:
    return get_client()[settings.DATABASE_NAME]


async def is_db_ready() -> bool:
    try:
        await get_db().command("ping")
        return True
    except Exception:
        return False
