from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase

from app.core.config import settings

_client: AsyncIOMotorClient | None = None


def get_client() -> AsyncIOMotorClient:
    """Return a process-local Motor client."""
    global _client
    if _client is None:
        _client = AsyncIOMotorClient(settings.MONGO_URI)
    return _client


def reset_client() -> None:
    """Close and drop the cached client."""
    global _client
    if _client is not None:
        _client.close()
    _client = None


def get_db() -> AsyncIOMotorDatabase:
    """Return the RAG-owned MongoDB database (query_logs)."""
    return get_client()[settings.DATABASE_NAME]


def get_repo_sync_db() -> AsyncIOMotorDatabase:
    """Return the repo-sync database (repositories, indexing_runs) — read-only."""
    return get_client()[settings.INDEXING_RUNS_DATABASE]


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