"""Unit tests covering the controller pipeline description API."""

#  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 mafw.steering_gui.controllers.steering_controller import SteeringController
from mafw.steering_gui.models.steering_tree_model import SteeringTreeModel, SteeringTreeRoles

pytestmark = pytest.mark.gui


def test_tree_model_exposes_top_level_sections() -> None:
    """Ensure the tree model exposes the fixed sections plus the processors branch."""

    controller = SteeringController()
    pipeline = controller.build_pipeline()
    model = SteeringTreeModel(controller, pipeline)
    root_index = model.index(0, 0)
    assert root_index.isValid()
    section_keys = tuple(
        model.data(model.index(row, 0, root_index), SteeringTreeRoles.SECTION_KEY)
        for row in range(model.rowCount(root_index))
    )
    assert section_keys == ('globals', 'database', 'ui', 'processors')


def test_build_pipeline_uses_processors_to_run_order() -> None:
    """Ensure only the processors listed in processors_to_run appear in the pipeline."""

    controller = SteeringController()
    controller.set_processor_parameter('Hidden', 'alpha', 1)
    controller.add_processor_to_run_list('First')
    controller.add_processor_to_run_list('Second')
    controller.add_processor_to_run_list('GroupOne')
    controller.add_group('GroupOne', ['First'])

    pipeline = controller.build_pipeline()
    processor_labels = [item.name() for item in pipeline.items]

    assert processor_labels == ['First', 'Second', 'GroupOne']


def test_build_pipeline_expands_groups_run_items() -> None:
    """Ensure group entries expand to show their processors and nested groups."""

    controller = SteeringController()
    controller.add_processor_to_run_list('Base')
    controller.add_processor_to_run_list('Chain')
    controller.add_processor_to_run_list('Executor')
    controller.add_processor_to_run_list('ChainOfChains')
    controller.add_group('Chain', ['Base', 'Executor'])
    controller.add_group('ChainOfChains', ['Chain', 'UnseenProcessor'])

    pipeline = controller.build_pipeline()
    group_node = next(item for item in pipeline.items if item.name() == 'Chain')
    chain_children = [child.name() for child in group_node.children]
    assert chain_children == ['Base', 'Executor']

    chain_of_chains = next(item for item in pipeline.items if item.name() == 'ChainOfChains')
    assert [child.name() for child in chain_of_chains.children] == ['Chain', 'UnseenProcessor']
