#  Copyright 2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2

import pytest

pytest.importorskip('PySide6', reason='PySide6 is required for GUI tests')

from PySide6.QtCore import QModelIndex
from PySide6.QtWidgets import QApplication

from mafw.enumerators import LogicalOp
from mafw.steering.models import Condition, ConditionalFilterConfig, FieldInfo, ModelInfo, ProcessorConfig
from mafw.steering_gui.utils import coerce_name
from mafw.steering_gui.views.filter_editors import ConditionalFilterEditor, ConditionDefinition

pytestmark = pytest.mark.gui


@pytest.fixture(scope='session')
def qapp():
    if not QApplication.instance():
        return QApplication([])
    return QApplication.instance()


def test_conditional_filter_editor_init(qapp):
    """Test initialization of ConditionalFilterEditor."""
    editor = ConditionalFilterEditor()
    assert editor.findChild(ConditionDefinition) is not None


def test_conditional_filter_editor_set_config(qapp):
    """Test set_config populates the editor."""
    editor = ConditionalFilterEditor()

    config = ConditionalFilterConfig(name='test_filter', model='TestModel')
    # Manually populate model_info for test since model might not exist
    config.model_info = ModelInfo()
    config.model_info.field_info = {'field1': FieldInfo('field1', int), 'field2': FieldInfo('field2', str)}

    proc_config = ProcessorConfig(name='TestProcessor')

    editor.set_config(config, proc_config, QModelIndex())

    assert config.condition is not None
    assert config.then_clause is not None
    assert config.else_clause is None  # Unchecked by default

    # Check if we can toggle else
    editor._else_group.setChecked(True)
    assert config.else_clause is not None

    editor._else_group.setChecked(False)
    assert config.else_clause is None


def test_condition_definition(qapp):
    """Test ConditionDefinition standalone."""
    definition = ConditionDefinition()

    cond = Condition(operator=LogicalOp.EQ, value=10)
    config = ConditionalFilterConfig(name='test', model='Test')
    config.model_info = ModelInfo()
    config.model_info.field_info = {'a': FieldInfo('a', int)}

    definition.set_condition(cond, config, 'a')

    assert definition._condition == cond
    assert definition._condition_name == 'a'

    # Change operator
    definition._operator_combo.setCurrentIndex(1)  # Should be NE
    assert cond.operator != LogicalOp.EQ


def test_coerce_name():
    """Test that whitespace is replaced by underscores."""
    assert coerce_name('test filter') == 'test_filter'
    assert coerce_name('test\tfilter') == 'test_filter'
    assert coerce_name('test  filter') == 'test_filter'
    assert coerce_name('test\nfilter') == 'test_filter'


def test_conditional_filter_editor_name_normalization(qapp):
    """Test that name edit in ConditionalFilterEditor coerces whitespace."""
    editor = ConditionalFilterEditor()
    config = ConditionalFilterConfig(name='test', model='Test')
    config.model_info = ModelInfo()
    config.model_info.field_info = {'a': FieldInfo('a', int)}
    editor.set_config(config, ProcessorConfig(name='P'), QModelIndex())

    editor._name_edit.setText('new name')
    assert config.name == 'new_name'
    assert editor._name_edit.text() == 'new_name'
