# #region SupersetDatabasesMixin [C:3] [TYPE Module] [SEMANTICS superset, search, superset-databases-mixin]
# @LAYER Infrastructure
# @BRIEF Database domain mixin for SupersetClient — list, get, summary, by_uuid.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
from typing import Any, cast

from ..logger import belief_scope, logger as app_logger

app_logger = cast(Any, app_logger)
# #region SupersetDatabasesMixin [C:3] [TYPE Class]
# @BRIEF Mixin providing all database-related Superset API operations.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
class SupersetDatabasesMixin:
    # #region SupersetClientGetDatabases [TYPE Function] [C:3]
    # @PURPOSE: Получает полный список баз данных.
    # @RELATION CALLS -> [SupersetClientFetchAllPages]
    def get_databases(self, query: dict | None = None) -> tuple[int, list[dict]]:
        with belief_scope("get_databases"):
            app_logger.info("[get_databases][Enter] Fetching databases.")
            validated_query = self._validate_query_params(query or {})
            if "columns" not in validated_query:
                validated_query["columns"] = []
            paginated_data = self._fetch_all_pages(
                endpoint="/database/",
                pagination_options={
                    "base_query": validated_query,
                    "results_field": "result",
                },
            )
            total_count = len(paginated_data)
            app_logger.reflect(f"Found {total_count} databases.", extra={"src": "get_databases"})
            return total_count, paginated_data
    # #endregion SupersetClientGetDatabases
    # #region SupersetClientGetDatabase [TYPE Function] [C:3]
    # @PURPOSE: Получает информацию о конкретной базе данных по её ID.
    # @RELATION CALLS -> [APIClient]
    def get_database(self, database_id: int) -> dict:
        with belief_scope("get_database"):
            app_logger.info("[get_database][Enter] Fetching database %s.", database_id)
            response = self.network.request(
                method="GET", endpoint=f"/database/{database_id}"
            )
            response = cast(dict, response)
            app_logger.reflect(f"Got database {database_id}.", extra={"src": "get_database"})
            return response
    # #endregion SupersetClientGetDatabase
    # #region SupersetClientGetDatabasesSummary [TYPE Function] [C:3]
    # @PURPOSE: Fetch a summary of databases including uuid, name, and engine.
    # @RELATION CALLS -> [SupersetClientGetDatabases]
    def get_databases_summary(self) -> list[dict]:
        with belief_scope("SupersetClient.get_databases_summary"):
            query = {"columns": ["id", "uuid", "database_name", "backend"]}
            _, databases = self.get_databases(query=query)
            # Map 'backend' to 'engine' for consistency with contracts
            for db in databases:
                db["engine"] = db.pop("backend", None)
            return databases
    # #endregion SupersetClientGetDatabasesSummary
    # #region SupersetClientGetDatabaseByUuid [TYPE Function] [C:3]
    # @PURPOSE: Find a database by its UUID.
    # @RELATION CALLS -> [SupersetClientGetDatabases]
    def get_database_by_uuid(self, db_uuid: str) -> dict | None:
        with belief_scope("SupersetClient.get_database_by_uuid", f"uuid={db_uuid}"):
            query = {"filters": [{"col": "uuid", "op": "eq", "value": db_uuid}]}
            _, databases = self.get_databases(query=query)
            return databases[0] if databases else None
    # #endregion SupersetClientGetDatabaseByUuid
# #endregion SupersetDatabasesMixin
# #endregion SupersetDatabasesMixin
