#  Copyright 2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2
"""Unit tests for the AddProcessorDialog widget.

:Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
:Description: Ensure selection enables the Add button and selected names are reported.
"""

from __future__ import annotations

import pytest

# Skip this module if PySide6 is not available
pytest.importorskip('PySide6', reason='PySide6 is required for GUI tests')
from PySide6.QtCore import QItemSelectionModel
from PySide6.QtWidgets import QApplication

from mafw.steering_gui.dialogs.add_processor_dialog import AddProcessorDialog

pytestmark = pytest.mark.gui


@pytest.fixture(scope='session')
def qapp() -> QApplication:
    """Ensure a single QApplication instance exists for all GUI tests."""

    app = QApplication.instance()
    if app is None:
        app = QApplication([])
    return app


def test_add_button_enables_on_selection(qapp: QApplication) -> None:
    """Selecting an item should enable the Add button."""

    dialog = AddProcessorDialog(['ProcA', 'ProcB'])
    assert dialog.add_button.isEnabled() is False

    index = dialog.list_view.model().index(0, 0)
    dialog.list_view.selectionModel().select(index, QItemSelectionModel.SelectionFlag.Select)
    dialog._update_add_enabled()

    assert dialog.add_button.isEnabled() is True


def test_selected_names_returns_selection(qapp: QApplication) -> None:
    """Selected names should match the list view selection."""

    dialog = AddProcessorDialog(['ProcA', 'ProcB', 'ProcC'])
    selection = dialog.list_view.selectionModel()
    model = dialog.list_view.model()
    selection.select(model.index(0, 0), QItemSelectionModel.SelectionFlag.Select)
    selection.select(model.index(2, 0), QItemSelectionModel.SelectionFlag.Select)

    assert sorted(dialog.selected_names()) == ['ProcA', 'ProcC']


def test_filtering(qapp: QApplication) -> None:
    """Typing in the filter edit should update the visible items."""

    processors = ['Alpha', 'Beta', 'Gamma', 'Delta', 'Zero']
    dialog = AddProcessorDialog(processors)

    # Initially all items are visible in the proxy model
    assert dialog.list_view.model().rowCount() == 5

    # Filter for 'a' (case-insensitive)
    dialog.filter_edit.setText('a')
    # Alpha, Beta, Gamma, Delta contain 'a' (or 'A'). Zero does not.
    assert dialog.list_view.model().rowCount() == 4

    # Filter for 'Al'
    dialog.filter_edit.setText('Al')
    assert dialog.list_view.model().rowCount() == 1
    assert dialog.list_view.model().index(0, 0).data() == 'Alpha'

    # Clear filter
    dialog.filter_edit.clear()
    assert dialog.list_view.model().rowCount() == 5
