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

from __future__ import annotations

import pytest

pytest.importorskip('PySide6', reason='PySide6 is required for GUI tests')
from peewee import AutoField, IntegerField, TextField
from PySide6.QtCore import QModelIndex, Qt
from PySide6.QtWidgets import QApplication

from mafw.db.db_model import MAFwBaseModel, mafw_model_register
from mafw.steering.models import (
    Condition,
    FieldFilterConfig,
    ModelFilterConfig,
    ProcessorConfig,
)
from mafw.steering_gui.views.filter_editors import ModelFilterEditor

pytestmark = pytest.mark.gui


class ModelA(MAFwBaseModel):
    """A dummy model for testing."""

    id = AutoField(primary_key=True)
    name = TextField(help_text='The name field')
    count = IntegerField()


@pytest.fixture(scope='session')
def qapp() -> QApplication:
    app = QApplication.instance()
    if app is None:
        app = QApplication([])
    return app


def test_model_filter_editor_table_population(qapp: QApplication):
    """Verify that the table in ModelFilterEditor shows model fields."""
    mafw_model_register.register_model('model_a', ModelA)

    editor = ModelFilterEditor()
    model_config = ModelFilterConfig(name='test', model='model_a')
    # Add a simple condition for 'name'
    model_config.conditions['name'] = Condition('==', 'test')

    proc_config = ProcessorConfig(name='proc')
    # Add a composite filter for 'id'
    proc_config.filters['model_a'] = [
        model_config,
        FieldFilterConfig(name='f1', model='model_a', field_name='id'),
    ]

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

    table = editor._fields_table
    table_model = table.model()
    assert table_model.rowCount() == 3  # id, name, count

    # Check order: id, name, count (as defined in ModelA)
    assert table_model.data(table_model.index(0, 0)) == 'id'
    assert table_model.data(table_model.index(1, 0)) == 'name'
    assert table_model.data(table_model.index(2, 0)) == 'count'

    assert table_model.data(table_model.index(0, 2)) == 'Composite'
    assert table_model.data(table_model.index(1, 2)) == 'Simple'
    assert table_model.data(table_model.index(2, 2)) == 'None'

    # Check tooltips
    assert table_model.data(table_model.index(1, 0), role=Qt.ItemDataRole.ToolTipRole) == 'The name field'
