# #region Test.SupersetContextFilters [C:3] [TYPE Module] [SEMANTICS test, superset, filter, extract, mixin]
# @BRIEF Tests for _filters.py — SupersetContextFiltersExtractMixin._extract_imported_filters.
# @RELATION BINDS_TO -> [SupersetContextFiltersExtractMixin]

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "src"))

import os
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing")
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")

import pytest

from src.core.utils.superset_context_extractor._filters import SupersetContextFiltersExtractMixin


class _TestExtractor(SupersetContextFiltersExtractMixin):
    """Concrete test class for the mixin."""
    pass


@pytest.fixture
def extractor():
    return _TestExtractor()


class TestExtractImportedFilters:
    """_extract_imported_filters — normalize filters from various sources."""

    def test_native_filters_list(self, extractor):
        """native_filters list produces filter entries."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"filter_name": "country", "column": "country", "value": ["US", "CA"]},
                {"filter_name": "year", "column": "year", "val": "2024"},
            ]
        })
        assert len(result) == 2
        assert result[0]["filter_name"] == "country"
        assert result[1]["filter_name"] == "year"

    def test_native_filters_column_only(self, extractor):
        """Filter with column but no value => partial recovery."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"column": "country"}
            ]
        })
        assert len(result) == 1
        assert result[0]["recovery_status"] == "partial"
        assert result[0]["requires_confirmation"] is True

    def test_native_filters_with_name(self, extractor):
        """Filter with name fallback."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"name": "my_filter", "value": "val"}
            ]
        })
        assert result[0]["filter_name"] == "my_filter"

    def test_native_filters_no_name_fallback_index(self, extractor):
        """Filter with no name falls back to index."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"value": "val"}
            ]
        })
        assert result[0]["filter_name"] == "native_filter_0"

    def test_native_filters_skip_non_dict(self, extractor):
        """Non-dict items in native_filters are skipped."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"column": "country", "value": "US"},
                "not_a_dict",
                42,
            ]
        })
        assert len(result) == 1

    def test_native_filters_op_inference_list(self, extractor):
        """List value infers op='IN'."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"column": "country", "value": ["US", "CA"]}
            ]
        })
        clause = result[0]["normalized_value"]["filter_clauses"][0]
        assert clause["op"] == "IN"

    def test_native_filters_op_inference_scalar(self, extractor):
        """Scalar value infers op='=='."""
        result = extractor._extract_imported_filters({
            "native_filters": [
                {"column": "country", "value": "US"}
            ]
        })
        clause = result[0]["normalized_value"]["filter_clauses"][0]
        assert clause["op"] == "=="

    def test_dataMask_with_filterState(self, extractor):
        """dataMask with filterState extracts value."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "filter_key": {
                    "filterState": {"label": "Country", "value": "US"},
                    "extraFormData": {},
                }
            }
        })
        assert len(result) == 1
        assert result[0]["raw_value"] == "US"
        assert result[0]["recovery_status"] == "recovered"

    def test_dataMask_extra_form_data_filters(self, extractor):
        """dataMask extraFormData.filters extracts clauses."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country", "op": "IN", "val": ["US"]}]
                    }
                }
            }
        })
        assert len(result) >= 1
        clauses = result[0]["normalized_value"]["filter_clauses"]
        assert len(clauses) == 1
        assert clauses[0]["col"] == "country"

    def test_dataMask_raw_value_from_clauses(self, extractor):
        """raw_value derived from filter_clauses when no filterState."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country", "op": "IN", "val": "US"}]
                    }
                }
            }
        })
        assert result[0]["raw_value"] == "US"
        assert result[0]["recovery_status"] == "recovered"

    def test_dataMask_time_extra_form_data(self, extractor):
        """extraFormData time fields provide raw_value."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {"time_range": "Last 30 days"}
                }
            }
        })
        assert result[0]["raw_value"] == "Last 30 days"

    def test_dataMask_no_value_partial(self, extractor):
        """dataMask without value yields partial recovery."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {}
                }
            }
        })
        assert result[0]["recovery_status"] == "partial"

    def test_native_filter_state(self, extractor):
        """native_filter_state extracts filters."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "filterState": {"label": "Country", "value": "US"},
                    "extraFormData": {},
                }
            }
        })
        assert len(result) >= 1
        assert result[0]["raw_value"] == "US"
        assert result[0]["source"] == "superset_native_filters_key"

    def test_form_data_extra_filters(self, extractor):
        """form_data.extra_filters produces filter entries."""
        result = extractor._extract_imported_filters({
            "form_data": {
                "extra_filters": [
                    {"col": "country", "op": "IN", "val": ["US"]},
                    {"col": "year", "op": "==", "val": 2024},
                ]
            }
        })
        assert len(result) == 2
        assert result[0]["filter_name"] == "country"
        assert result[1]["filter_name"] == "year"

    def test_form_data_extra_filters_skip_non_dict(self, extractor):
        """Non-dict items in extra_filters are skipped."""
        result = extractor._extract_imported_filters({
            "form_data": {
                "extra_filters": [
                    {"col": "country", "val": "US"},
                    "not_a_dict",
                ]
            }
        })
        assert len(result) == 1

    def test_form_data_filter_name_fallback(self, extractor):
        """Filter without col/column falls back to index."""
        result = extractor._extract_imported_filters({
            "form_data": {
                "extra_filters": [
                    {"val": "test"}
                ]
            }
        })
        assert "extra_filter_0" in result[0]["filter_name"]

    def test_empty_query_state(self, extractor):
        """Empty query state returns empty list."""
        result = extractor._extract_imported_filters({})
        assert result == []

    def test_native_filters_not_list(self, extractor):
        """native_filters that is not a list is ignored."""
        result = extractor._extract_imported_filters({
            "native_filters": "not_a_list"
        })
        assert result == []
