"""GUI tests covering the UIEditor combo built around UI plugins."""

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

import pytest

pytest.importorskip('PySide6', reason='PySide6 is required for GUI tests')
from PySide6.QtWidgets import QApplication

from mafw.steering_gui.views.ui_editor import UIEditor

pytestmark = pytest.mark.gui


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

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


def test_loading_state_shows_placeholder(qapp: QApplication) -> None:
    """The combo displays a loading placeholder and remains disabled until plugins finish."""

    editor = UIEditor()
    editor.set_available_interfaces(None)

    assert editor.interface_combo.count() == 1
    assert editor.interface_combo.itemText(0) == 'Loading available UIs...'
    assert not editor.interface_combo.isEnabled()


def test_set_current_interface_before_list_preserves_selection(qapp: QApplication) -> None:
    """Setting the controller value before plugin names arrive still selects it later."""

    editor = UIEditor()
    editor.set_current_interface('console')
    editor.set_available_interfaces(['rich', 'console'])

    assert editor.interface_combo.currentText() == 'console'
    assert editor.interface_combo.count() == 2


def test_interface_changed_signal_emits_for_user_choice(qapp: QApplication) -> None:
    """Signals fire when the user selects an actual UI name and not for programmatic updates."""

    editor = UIEditor()
    editor.set_available_interfaces(['rich', 'console'])
    events: list[str] = []
    editor.interface_changed.connect(events.append)

    editor.interface_combo.setCurrentIndex(1)
    assert events == ['console']

    editor.set_current_interface('rich')
    assert events == ['console']
