# #region Test.SupersetContextFiltersExtra [C:2] [TYPE Module] [SEMANTICS test, superset, filter, edge]
# @BRIEF Extra tests for _filters.py — edge cases that hit lines 76, 107, 144, 167, 173-178, 182-193.
# @RELATION BINDS_TO -> [SupersetContextFiltersExtractMixin]

from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).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 TestExtractImportedFiltersExtra:
    """Extra edge cases for _extract_imported_filters."""

    def test_dataMask_non_dict_item_skipped(self, extractor):
        """dataMask non-dict item is skipped (line 76)."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": "not_a_dict",
                "NATIVE-2": {"filterState": {"label": "Country", "value": "US"}},
            }
        })
        assert len(result) == 1
        assert result[0]["raw_value"] == "US"

    def test_dataMask_filter_state_values_fallback(self, extractor):
        """filterState 'values' used when 'value' is None (line 107)."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "filterState": {"label": "Country", "values": ["US", "CA"]},
                    "extraFormData": {},
                }
            }
        })
        assert result[0]["raw_value"] == ["US", "CA"]

    def test_native_filter_state_non_dict_skipped(self, extractor):
        """native_filter_state non-dict item skipped (line 144)."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": "not_a_dict",
                "NATIVE-2": {"filterState": {"value": "US"}, "extraFormData": {}},
            }
        })
        assert len(result) == 1
        assert result[0]["raw_value"] == "US"

    def test_native_filter_state_extra_form_data_filters(self, extractor):
        """native_filter_state extraFormData.filters extracts clauses (line 167)."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "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_native_filter_state_raw_value_from_clauses(self, extractor):
        """native_filter_state: raw_value derived from filter_clauses (lines 173-178)."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country", "op": "IN", "val": "US"}]
                    }
                }
            }
        })
        assert result[0]["raw_value"] == "US"
        assert result[0]["recovery_status"] == "recovered"

    def test_native_filter_state_raw_value_from_clauses_value_key(self, extractor):
        """native_filter_state: raw_value from 'value' key when 'val' absent."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country", "op": "IN", "value": "Canada"}]
                    }
                }
            }
        })
        assert result[0]["raw_value"] == "Canada"

    def test_native_filter_state_time_fields(self, extractor):
        """native_filter_state: time fields provide raw_value (lines 182-193)."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {"time_range": "Last 7 days"}
                }
            }
        })
        assert result[0]["raw_value"] == "Last 7 days"
        assert result[0]["recovery_status"] == "recovered"

    def test_native_filter_state_time_grain_field(self, extractor):
        """native_filter_state: time_grain_sqla field."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {"time_grain_sqla": "P1D"}
                }
            }
        })
        assert result[0]["raw_value"] == "P1D"

    def test_native_filter_state_time_column_field(self, extractor):
        """native_filter_state: time_column field."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {"time_column": "created_at"}
                }
            }
        })
        assert result[0]["raw_value"] == "created_at"

    def test_native_filter_state_granularity_field(self, extractor):
        """native_filter_state: granularity field."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-1": {
                    "extraFormData": {"granularity": "day"}
                }
            }
        })
        assert result[0]["raw_value"] == "day"

    def test_dataMask_raw_value_from_clauses_value_key(self, extractor):
        """dataMask: raw_value from 'value' key when 'val' absent."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country", "op": "IN", "value": "UK"}]
                    }
                }
            }
        })
        assert result[0]["raw_value"] == "UK"
        assert result[0]["recovery_status"] == "recovered"

    def test_dataMask_time_extra_form_data_time_grain(self, extractor):
        """dataMask: time_grain_sqla extraFormData field."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {"time_grain_sqla": "P1M"}
                }
            }
        })
        assert result[0]["raw_value"] == "P1M"

    def test_dataMask_extra_form_data_has_filters_without_val(self, extractor):
        """dataMask: extraFormData filters without val/value yields partial."""
        result = extractor._extract_imported_filters({
            "dataMask": {
                "NATIVE-1": {
                    "extraFormData": {
                        "filters": [{"col": "country"}]
                    }
                }
            }
        })
        # Should still get a filter entry, raw_value is None from filter clauses
        # and no time fields present
        assert result[0]["raw_value"] is None
        assert result[0]["recovery_status"] == "partial"

    def test_native_filter_state_filter_id_fallback(self, extractor):
        """native_filter_state: filter uses item id or falls back to key."""
        result = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-KEY": {
                    "filterState": {"value": "test_val"},
                    "extraFormData": {},
                }
            }
        })
        # No 'id' in item, so falls back to "NATIVE-KEY"
        assert result[0]["filter_name"] == "NATIVE-KEY"

        result2 = extractor._extract_imported_filters({
            "native_filter_state": {
                "NATIVE-KEY": {
                    "id": "OVERRIDE-ID",
                    "filterState": {"value": "test_val"},
                    "extraFormData": {},
                }
            }
        })
        assert result2[0]["filter_name"] == "OVERRIDE-ID"
# #endregion Test.SupersetContextFiltersExtra
