# #region SupersetContextFiltersExtractMixin [C:3] [TYPE Module] [SEMANTICS superset, filter, native, context, extract]
# @LAYER Infrastructure
# @BRIEF Extract normalized imported filters from decoded Superset query state (native_filters, dataMask, native_filter_state, form_data).
# @RELATION DEPENDS_ON -> [SupersetContextExtractorBase]
# #endregion SupersetContextFiltersExtractMixin
# #region _filters_imports [TYPE Block]
from __future__ import annotations

from copy import deepcopy
from typing import Any, cast

from ...logger import logger as app_logger

app_logger = cast(Any, app_logger)
# #endregion _filters_imports
# #region SupersetContextFiltersExtractMixin [C:3] [TYPE Class]
# @BRIEF Mixin providing query-state filter extraction for the composed SupersetContextExtractor.
class SupersetContextFiltersExtractMixin:
    # #region SupersetContextFiltersExtractMixin._extract_imported_filters [TYPE Function] [C:2]
    # @PURPOSE: Normalize imported filters from decoded query state without fabricating missing values.
    def _extract_imported_filters(
        self, query_state: dict[str, Any]
    ) -> list[dict[str, Any]]:
        imported_filters: list[dict[str, Any]] = []
        native_filters_payload = query_state.get("native_filters")
        if isinstance(native_filters_payload, list):
            for index, item in enumerate(native_filters_payload):
                if not isinstance(item, dict):
                    continue
                filter_name = (
                    item.get("filter_name")
                    or item.get("column")
                    or item.get("name")
                    or f"native_filter_{index}"
                )
                direct_clause = None
                if item.get("column") and ("value" in item or "val" in item):
                    direct_clause = {
                        "col": item.get("column"),
                        "op": item.get("op")
                        or (
                            "IN"
                            if isinstance(item.get("value"), list)
                            else "=="
                        ),
                        "val": item.get("val", item.get("value")),
                    }
                imported_filters.append(
                    {
                        "filter_name": str(filter_name),
                        "raw_value": item.get("value"),
                        "display_name": item.get("label") or item.get("name"),
                        "normalized_value": {
                            "filter_clauses": [direct_clause]
                            if isinstance(direct_clause, dict)
                            else [],
                            "extra_form_data": {},
                            "value_origin": "native_filters",
                        },
                        "source": "superset_url",
                        "recovery_status": "recovered"
                        if item.get("value") is not None
                        else "partial",
                        "requires_confirmation": item.get("value") is None,
                        "notes": "Recovered from Superset native filter URL state",
                    }
                )
        # Extract filters from permalink dataMask
        dashboard_data_mask = query_state.get("dataMask")
        if isinstance(dashboard_data_mask, dict):
            for filter_key, item in dashboard_data_mask.items():
                if not isinstance(item, dict):
                    continue
                filter_state = item.get("filterState")
                extra_form_data = item.get("extraFormData")
                display_name = None
                raw_value = None
                normalized_value = {
                    "filter_clauses": [],
                    "extra_form_data": deepcopy(extra_form_data)
                    if isinstance(extra_form_data, dict)
                    else {},
                    "value_origin": "unresolved",
                }
                if isinstance(filter_state, dict):
                    display_name = filter_state.get("label")
                    raw_value = filter_state.get("value") or filter_state.get(
                        "values"
                    )
                    if raw_value is not None:
                        normalized_value["value_origin"] = "filter_state"
                if isinstance(extra_form_data, dict):
                    extra_filters = extra_form_data.get("filters")
                    if isinstance(extra_filters, list):
                        normalized_value["filter_clauses"] = [
                            deepcopy(extra_filter)
                            for extra_filter in extra_filters
                            if isinstance(extra_filter, dict)
                        ]
                if raw_value is None and normalized_value["filter_clauses"]:
                    first_filter = normalized_value["filter_clauses"][0]
                    raw_value = first_filter.get("val")
                    if raw_value is None:
                        raw_value = first_filter.get("value")
                    if raw_value is not None:
                        normalized_value["value_origin"] = (
                            "extra_form_data.filters"
                        )
                if raw_value is None and isinstance(extra_form_data, dict):
                    for field in [
                        "time_range",
                        "time_grain_sqla",
                        "time_column",
                        "granularity",
                    ]:
                        if field in extra_form_data:
                            raw_value = extra_form_data[field]
                            normalized_value["value_origin"] = (
                                f"extra_form_data.{field}"
                            )
                            break
                imported_filters.append(
                    {
                        "filter_name": str(item.get("id") or filter_key),
                        "raw_value": raw_value,
                        "display_name": display_name,
                        "normalized_value": normalized_value,
                        "source": "superset_permalink",
                        "recovery_status": "recovered"
                        if raw_value is not None
                        else "partial",
                        "requires_confirmation": raw_value is None,
                        "notes": "Recovered from Superset dashboard permalink state",
                    }
                )
        # Extract filters from native_filter_state (fetched via native_filters_key)
        native_filter_state = query_state.get("native_filter_state")
        if isinstance(native_filter_state, dict):
            for filter_key, item in native_filter_state.items():
                if not isinstance(item, dict):
                    continue
                filter_id = item.get("id") or filter_key
                filter_state = item.get("filterState")
                extra_form_data = item.get("extraFormData")
                display_name = None
                raw_value = None
                normalized_value = {
                    "filter_clauses": [],
                    "extra_form_data": deepcopy(extra_form_data)
                    if isinstance(extra_form_data, dict)
                    else {},
                    "value_origin": "unresolved",
                }
                if isinstance(filter_state, dict):
                    display_name = filter_state.get("label")
                    raw_value = filter_state.get("value") or filter_state.get(
                        "values"
                    )
                    if raw_value is not None:
                        normalized_value["value_origin"] = "filter_state"
                if isinstance(extra_form_data, dict):
                    extra_filters = extra_form_data.get("filters")
                    if isinstance(extra_filters, list):
                        normalized_value["filter_clauses"] = [
                            deepcopy(extra_filter)
                            for extra_filter in extra_filters
                            if isinstance(extra_filter, dict)
                        ]
                if raw_value is None and normalized_value["filter_clauses"]:
                    first_filter = normalized_value["filter_clauses"][0]
                    raw_value = first_filter.get("val")
                    if raw_value is None:
                        raw_value = first_filter.get("value")
                    if raw_value is not None:
                        normalized_value["value_origin"] = (
                            "extra_form_data.filters"
                        )
                if raw_value is None and isinstance(extra_form_data, dict):
                    for field in [
                        "time_range",
                        "time_grain_sqla",
                        "time_column",
                        "granularity",
                    ]:
                        if field in extra_form_data:
                            raw_value = extra_form_data[field]
                            normalized_value["value_origin"] = (
                                f"extra_form_data.{field}"
                            )
                            break
                imported_filters.append(
                    {
                        "filter_name": str(filter_id),
                        "raw_value": raw_value,
                        "display_name": display_name,
                        "normalized_value": normalized_value,
                        "source": "superset_native_filters_key",
                        "recovery_status": "recovered"
                        if raw_value is not None
                        else "partial",
                        "requires_confirmation": raw_value is None,
                        "notes": "Recovered from Superset native_filters_key state",
                    }
                )
        form_data_payload = query_state.get("form_data")
        if isinstance(form_data_payload, dict):
            extra_filters = form_data_payload.get("extra_filters") or []
            for index, item in enumerate(extra_filters):
                if not isinstance(item, dict):
                    continue
                filter_name = (
                    item.get("col")
                    or item.get("column")
                    or f"extra_filter_{index}"
                )
                imported_filters.append(
                    {
                        "filter_name": str(filter_name),
                        "raw_value": item.get("val"),
                        "display_name": item.get("label"),
                        "normalized_value": {
                            "filter_clauses": [deepcopy(item)],
                            "extra_form_data": {},
                            "value_origin": "form_data.extra_filters",
                        },
                        "source": "superset_url",
                        "recovery_status": "recovered"
                        if item.get("val") is not None
                        else "partial",
                        "requires_confirmation": item.get("val") is None,
                        "notes": "Recovered from Superset form_data extra_filters",
                    }
                )
        return imported_filters
    # #endregion SupersetContextFiltersExtractMixin._extract_imported_filters
# #endregion SupersetContextFiltersExtractMixin
