# #region SupersetChartsMixin [C:3] [TYPE Module] [SEMANTICS superset, chart, query, list, extract]
# @LAYER Infrastructure
# @BRIEF Chart domain mixin for SupersetClient — list, get, extract IDs from layout.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
import re
from typing import Any, cast

from ..logger import belief_scope, logger as app_logger

app_logger = cast(Any, app_logger)
# #region SupersetChartsMixin [C:3] [TYPE Class]
# @BRIEF Mixin providing all chart-related Superset API operations.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
class SupersetChartsMixin:
    # #region SupersetClientGetChart [TYPE Function] [C:3]
    # @PURPOSE: Fetches a single chart by ID.
    # @RELATION CALLS -> [APIClient]
    def get_chart(self, chart_id: int) -> dict:
        with belief_scope("SupersetClient.get_chart", f"id={chart_id}"):
            response = self.network.request(method="GET", endpoint=f"/chart/{chart_id}")
            return cast(dict, response)
    # #endregion SupersetClientGetChart
    # #region SupersetClientGetCharts [TYPE Function] [C:3]
    # @PURPOSE: Fetches all charts with pagination support.
    # @RELATION CALLS -> [SupersetClientFetchAllPages]
    def get_charts(self, query: dict | None = None) -> tuple[int, list[dict]]:
        with belief_scope("get_charts"):
            validated_query = self._validate_query_params(query or {})
            if "columns" not in validated_query:
                validated_query["columns"] = ["id", "uuid", "slice_name", "viz_type"]
            paginated_data = self._fetch_all_pages(
                endpoint="/chart/",
                pagination_options={
                    "base_query": validated_query,
                    "results_field": "result",
                },
            )
            return len(paginated_data), paginated_data
    # #endregion SupersetClientGetCharts
    # #region SupersetClientExtractChartIdsFromLayout [TYPE Function] [C:1]
    # @PURPOSE: Traverses dashboard layout metadata and extracts chart IDs from common keys.
    def _extract_chart_ids_from_layout(
        self, payload: Any
    ) -> set:
        with belief_scope("_extract_chart_ids_from_layout"):
            found = set()
            def walk(node):
                if isinstance(node, dict):
                    for key, value in node.items():
                        if key in ("chartId", "chart_id", "slice_id", "sliceId"):
                            try:
                                found.add(int(value))
                            except (TypeError, ValueError):
                                app_logger.debug("Could not parse chart id value: %s", value)
                        if key == "id" and isinstance(value, str):
                            match = re.match(r"^CHART-(\d+)$", value)
                            if match:
                                try:
                                    found.add(int(match.group(1)))
                                except ValueError:
                                    app_logger.debug("Could not parse CHART-N id: %s", match.group(1))
                        walk(value)
                elif isinstance(node, list):
                    for item in node:
                        walk(item)
            walk(payload)
            return found
    # #endregion SupersetClientExtractChartIdsFromLayout
# #endregion SupersetChartsMixin
# #endregion SupersetChartsMixin
