# #region SupersetDashboardsFiltersMixin [C:3] [TYPE Module] [SEMANTICS superset, dashboard, filter, native, advanced]
# @LAYER Infrastructure
# @BRIEF Dashboard native filter extraction mixin for SupersetClient.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
import json
from typing import Any, cast

from ..logger import belief_scope, logger as app_logger

app_logger = cast(Any, app_logger)
# #region SupersetDashboardsFiltersMixin [C:3] [TYPE Class]
# @BRIEF Mixin providing dashboard native filter extraction from permalink and URL state.
# @RELATION DEPENDS_ON -> [SupersetClientBase]
class SupersetDashboardsFiltersMixin:
    # #region SupersetClientGetDashboard [TYPE Function] [C:3]
    # @PURPOSE: Fetches a single dashboard by ID or slug.
    # @RELATION CALLS -> [APIClient]
    def get_dashboard(self, dashboard_ref: int | str) -> dict:
        with belief_scope("SupersetClient.get_dashboard", f"ref={dashboard_ref}"):
            response = self.network.request(
                method="GET", endpoint=f"/dashboard/{dashboard_ref}"
            )
            return cast(dict, response)
    # #endregion SupersetClientGetDashboard
    # #region SupersetClientGetDashboardPermalinkState [TYPE Function] [C:2]
    # @PURPOSE: Fetches stored dashboard permalink state by permalink key.
    # @RELATION CALLS -> [APIClient]
    def get_dashboard_permalink_state(self, permalink_key: str) -> dict:
        with belief_scope(
            "SupersetClient.get_dashboard_permalink_state", f"key={permalink_key}"
        ):
            response = self.network.request(
                method="GET", endpoint=f"/dashboard/permalink/{permalink_key}"
            )
            return cast(dict, response)
    # #endregion SupersetClientGetDashboardPermalinkState
    # #region SupersetClientGetNativeFilterState [TYPE Function] [C:2]
    # @PURPOSE: Fetches stored native filter state by filter state key.
    # @RELATION CALLS -> [APIClient]
    def get_native_filter_state(
        self, dashboard_id: int | str, filter_state_key: str
    ) -> dict:
        with belief_scope(
            "SupersetClient.get_native_filter_state",
            f"dashboard={dashboard_id}, key={filter_state_key}",
        ):
            response = self.network.request(
                method="GET",
                endpoint=f"/dashboard/{dashboard_id}/filter_state/{filter_state_key}",
            )
            return cast(dict, response)
    # #endregion SupersetClientGetNativeFilterState
    # #region SupersetClientExtractNativeFiltersFromPermalink [TYPE Function] [C:3]
    # @PURPOSE: Extract native filters dataMask from a permalink key.
    # @RELATION CALLS -> [SupersetClientGetDashboardPermalinkState]
    def extract_native_filters_from_permalink(self, permalink_key: str) -> dict:
        with belief_scope(
            "SupersetClient.extract_native_filters_from_permalink",
            f"key={permalink_key}",
        ):
            permalink_response = self.get_dashboard_permalink_state(permalink_key)
            result = permalink_response.get("result", permalink_response)
            state = result.get("state", result)
            data_mask = state.get("dataMask", {})
            extracted_filters = {}
            for filter_id, filter_data in data_mask.items():
                if not isinstance(filter_data, dict):
                    continue
                extracted_filters[filter_id] = {
                    "extraFormData": filter_data.get("extraFormData", {}),
                    "filterState": filter_data.get("filterState", {}),
                    "ownState": filter_data.get("ownState", {}),
                }
            return {
                "dataMask": extracted_filters,
                "activeTabs": state.get("activeTabs", []),
                "anchor": state.get("anchor"),
                "chartStates": state.get("chartStates", {}),
                "permalink_key": permalink_key,
            }
    # #endregion SupersetClientExtractNativeFiltersFromPermalink
    # #region SupersetClientExtractNativeFiltersFromKey [TYPE Function] [C:3]
    # @PURPOSE: Extract native filters from a native_filters_key URL parameter.
    # @RELATION CALLS -> [SupersetClientGetNativeFilterState]
    def extract_native_filters_from_key(
        self, dashboard_id: int | str, filter_state_key: str
    ) -> dict:
        with belief_scope(
            "SupersetClient.extract_native_filters_from_key",
            f"dashboard={dashboard_id}, key={filter_state_key}",
        ):
            filter_response = self.get_native_filter_state(
                dashboard_id, filter_state_key
            )
            result = filter_response.get("result", filter_response)
            value = result.get("value")
            if isinstance(value, str):
                try:
                    parsed_value = json.loads(value)
                except json.JSONDecodeError as e:
                    app_logger.warning(
                        "[extract_native_filters_from_key][Warning] Failed to parse filter state JSON: %s",
                        e,
                    )
                    parsed_value = {}
            elif isinstance(value, dict):
                parsed_value = value
            else:
                parsed_value = {}
            extracted_filters = {}
            if "id" in parsed_value and "extraFormData" in parsed_value:
                filter_id = parsed_value.get("id", filter_state_key)
                extracted_filters[filter_id] = {
                    "extraFormData": parsed_value.get("extraFormData", {}),
                    "filterState": parsed_value.get("filterState", {}),
                    "ownState": parsed_value.get("ownState", {}),
                }
            else:
                for filter_id, filter_data in parsed_value.items():
                    if not isinstance(filter_data, dict):
                        continue
                    extracted_filters[filter_id] = {
                        "extraFormData": filter_data.get("extraFormData", {}),
                        "filterState": filter_data.get("filterState", {}),
                        "ownState": filter_data.get("ownState", {}),
                    }
            return {
                "dataMask": extracted_filters,
                "dashboard_id": dashboard_id,
                "filter_state_key": filter_state_key,
            }
    # #endregion SupersetClientExtractNativeFiltersFromKey
    # #region SupersetClientParseDashboardUrlForFilters [TYPE Function] [C:3]
    # @PURPOSE: Parse a Superset dashboard URL and extract native filter state if present.
    # @RELATION CALLS -> [SupersetClientExtractNativeFiltersFromPermalink]
    # @RELATION CALLS -> [SupersetClientExtractNativeFiltersFromKey]
    def parse_dashboard_url_for_filters(self, url: str) -> dict:
        with belief_scope(
            "SupersetClient.parse_dashboard_url_for_filters", f"url={url}"
        ):
            import urllib.parse
            parsed_url = urllib.parse.urlparse(url)
            query_params = urllib.parse.parse_qs(parsed_url.query)
            path_parts = parsed_url.path.rstrip("/").split("/")
            result = {
                "url": url,
                "dashboard_id": None,
                "filter_type": None,
                "filters": {},
            }
            # Check for permalink URL: /dashboard/p/{key}/ or /superset/dashboard/p/{key}/
            if "p" in path_parts:
                try:
                    p_index = path_parts.index("p")
                    if p_index + 1 < len(path_parts):
                        permalink_key = path_parts[p_index + 1]
                        filter_data = self.extract_native_filters_from_permalink(
                            permalink_key
                        )
                        result["filter_type"] = "permalink"
                        result["filters"] = filter_data
                        return result
                except ValueError:
                    app_logger.debug("Permalink key %s not found in URL", permalink_key)
            # Check for native_filters_key in query params
            native_filters_key = query_params.get("native_filters_key", [None])[0]
            if native_filters_key:
                dashboard_ref = None
                if "dashboard" in path_parts:
                    try:
                        dash_index = path_parts.index("dashboard")
                        if dash_index + 1 < len(path_parts):
                            potential_id = path_parts[dash_index + 1]
                            if potential_id not in ("p", "list", "new"):
                                dashboard_ref = potential_id
                    except ValueError:
                        app_logger.debug("Dashboard not found in path_parts for native_filters_key")
                if dashboard_ref:
                    resolved_id = None
                    try:
                        resolved_id = int(dashboard_ref)
                    except (ValueError, TypeError):
                        try:
                            dash_resp = self.get_dashboard(dashboard_ref)
                            dash_data = (
                                dash_resp.get("result", dash_resp)
                                if isinstance(dash_resp, dict)
                                else {}
                            )
                            raw_id = dash_data.get("id")
                            if raw_id is not None:
                                resolved_id = int(raw_id)
                        except Exception as e:
                            app_logger.warning(
                                "[parse_dashboard_url_for_filters][Warning] Failed to resolve dashboard slug '%s' to ID: %s",
                                dashboard_ref,
                                e,
                            )
                    if resolved_id is not None:
                        filter_data = self.extract_native_filters_from_key(
                            resolved_id, native_filters_key
                        )
                        result["filter_type"] = "native_filters_key"
                        result["dashboard_id"] = resolved_id
                        result["filters"] = filter_data
                        return result
                    else:
                        app_logger.warning(
                            "[parse_dashboard_url_for_filters][Warning] Could not resolve dashboard_id from URL for native_filters_key"
                        )
            # Check for native_filters in query params (direct filter values)
            native_filters = query_params.get("native_filters", [None])[0]
            if native_filters:
                try:
                    parsed_filters = json.loads(native_filters)
                    result["filter_type"] = "native_filters"
                    result["filters"] = {"dataMask": parsed_filters}
                    return result
                except json.JSONDecodeError as e:
                    app_logger.warning(
                        "[parse_dashboard_url_for_filters][Warning] Failed to parse native_filters JSON: %s",
                        e,
                    )
            return result
    # #endregion SupersetClientParseDashboardUrlForFilters
# #endregion SupersetDashboardsFiltersMixin
# #endregion SupersetDashboardsFiltersMixin
