"""GUI tests covering the manual steering text editor."""

#  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.builder import SteeringBuilder
from mafw.steering_gui.controllers.steering_controller import SteeringController
from mafw.steering_gui.dialogs.steering_text_editor import SteeringTextEditor

pytestmark = pytest.mark.gui


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

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


def _build_controller() -> SteeringController:
    builder = SteeringBuilder()
    builder.add_processor('Proc')
    controller = SteeringController(builder)
    controller.set_validation_level(None)
    return controller


def test_editor_validation_toggles_apply(qapp: QApplication) -> None:
    """Ensure validation status toggles the apply button."""

    controller = _build_controller()
    dialog = SteeringTextEditor(controller)
    dialog._validation_timer.stop()
    dialog._validate_current_text()
    assert dialog._apply_button.isEnabled() is True

    dialog._editor.setPlainText('analysis_name = "Run"\nprocessors_to_run = ["Proc"]\ninvalid =')
    dialog._validate_current_text()
    assert dialog._apply_button.isEnabled() is False
    dialog.close()


def test_apply_replaces_builder(qapp: QApplication) -> None:
    """Ensure applying valid TOML updates the controller builder."""

    controller = _build_controller()
    dialog = SteeringTextEditor(controller)
    dialog._validation_timer.stop()
    dialog._editor.setPlainText('analysis_name = "NewRun"\nprocessors_to_run = ["Proc"]\n\n[Proc]\n')
    dialog._apply_and_close()

    assert controller.get_analysis_name() == 'NewRun'
