#  Copyright 2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2
"""Editor showing metadata when the root node is selected.

:Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
:Description: Give users contextual guidance when the entire steering file is selected.
"""

from __future__ import annotations

from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
    QComboBox,
    QGridLayout,
    QGroupBox,
    QLabel,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

from mafw.steering.builder import ValidationLevel


class MetadataEditor(QWidget):
    """Provide a quick summary of the steering file when no specific section is active."""

    validation_level_changed = Signal(object)
    manual_edit_requested = Signal()

    def __init__(self, parent: QWidget | None = None) -> None:
        super().__init__(parent)
        layout = QVBoxLayout()
        layout.addWidget(QLabel('<b>MAFw Steering File</b>'))
        layout.addWidget(QLabel('Select a section on the left to configure its properties.'))

        steering_status_box = QGroupBox('Steering status')
        steering_status_layout = QVBoxLayout()
        self._analysis_label = QLabel()
        self._processor_label = QLabel()
        self._available_processors_label = QLabel()
        self._db_modules_label = QLabel()
        self._ui_label = QLabel()
        steering_status_layout.addWidget(self._analysis_label)
        steering_status_layout.addWidget(self._processor_label)
        steering_status_layout.addWidget(self._available_processors_label)
        steering_status_layout.addWidget(self._db_modules_label)
        steering_status_layout.addWidget(self._ui_label)
        steering_status_box.setLayout(steering_status_layout)

        validation_box = QGroupBox('Advanced options')
        validation_layout = QGridLayout()
        validation_layout.addWidget(QLabel('Validation level:'), 0, 0)
        self._validation_combo = QComboBox()
        self._validation_combo.addItem('None', None)
        for level in ValidationLevel:
            display = level.name.replace('_', ' ').title()
            self._validation_combo.addItem(display, level)
        self._validation_combo.currentIndexChanged.connect(self._emit_validation_level)
        validation_layout.addWidget(self._validation_combo, 0, 1)

        validation_layout.addWidget(QLabel('Edit current steering file in text editor:'), 1, 0)
        self._manual_edit_button = QPushButton('Open in editor')
        self._manual_edit_button.clicked.connect(self.manual_edit_requested.emit)
        validation_layout.addWidget(self._manual_edit_button, 1, 1)
        validation_box.setLayout(validation_layout)

        layout.addWidget(steering_status_box)
        layout.addWidget(validation_box)
        layout.addStretch(1)
        self.setLayout(layout)

    def update_summary(
        self,
        analysis_name: str | None,
        processor_count: int,
        available_processors: int | None = None,
        available_db_modules: int | None = None,
        available_uis: int | None = None,
    ) -> None:
        """Refresh the summary labels to match the loaded model."""

        if analysis_name:
            analysis_text = f'Analysis name: {analysis_name}'
        else:
            analysis_text = 'Analysis name: not set.'
        count_text = (
            f'{processor_count} processor{"s" if processor_count != 1 else ""} configured.'
            if processor_count
            else 'No processors configured yet.'
        )
        self._analysis_label.setText(analysis_text)
        self._processor_label.setText(count_text)
        self._available_processors_label.setText(
            f'Available processor types: {available_processors}'
            if available_processors is not None
            else 'Available processors: loading...'
        )
        self._db_modules_label.setText(
            f'DB modules loaded: {available_db_modules}'
            if available_db_modules is not None
            else 'DB modules loaded: loading...'
        )
        self._ui_label.setText(
            f'Available UIs: {available_uis}' if available_uis is not None else 'Available UIs: loading...'
        )

    def set_validation_level(self, level: ValidationLevel | None) -> None:
        """Update the combo to reflect the controller's validation preference."""

        target_index = 0
        for index in range(self._validation_combo.count()):
            if self._validation_combo.itemData(index) == level:
                target_index = index
                break
        previous = self._validation_combo.blockSignals(True)
        self._validation_combo.setCurrentIndex(target_index)
        self._validation_combo.blockSignals(previous)

    def _emit_validation_level(self, index: int) -> None:
        value = self._validation_combo.itemData(index)
        self.validation_level_changed.emit(value)
