"""Create Analysis Dialog."""

from typing import Any, Dict, Optional
import uuid

from .base_dialog import BaseDialog
from .engine_selection import get_simple_engine_choices, engine_description_for_value
from ..comment_formats import apply_sidecar
from ..models import Analysis, EngineType
from ..qt_compat import QComboBox, QDialog, QLabel, Qt, exec_dialog
from ..translator import tr, add_listener, remove_listener


class CreateProvenanceDialog(BaseDialog):
    """Dialog for creating a new Analysis under a Study."""

    def __init__(self, parent=None):
        """
        Initialize Create Analysis dialog

        Args:
            parent: Parent widget
        """
        super().__init__(tr("create_analysis.window_title"), parent, width=560, height=420)
        self.init_ui()
        self.retranslateUi()
        add_listener(self.retranslateUi)

    def init_ui(self):
        """Initialize dialog UI"""
        layout = self.create_main_layout()

        self.name_input = self.add_text_field(layout, tr("create_analysis.lbl_name"))

        self.description_input = self.add_rich_text_field(
            layout, tr("create_analysis.lbl_description")
        )

        self.engine_group_box, engine_form = self.add_form_group(layout, tr("create_analysis.group_first_task"))
        self.initial_engine_combo = QComboBox()
        for label, engine_type, description in get_simple_engine_choices():
            self.initial_engine_combo.addItem(label, engine_type.value)
            self.initial_engine_combo.setItemData(
                self.initial_engine_combo.count() - 1,
                description,
                Qt.ItemDataRole.ToolTipRole,
            )
        self.initial_engine_combo.currentIndexChanged.connect(self._refresh_engine_description)
        self.engine_label = QLabel(tr("create_analysis.lbl_engine"))
        engine_form.addRow(self.engine_label, self.initial_engine_combo)

        self.engine_description_label = QLabel("")
        self.engine_description_label.setWordWrap(True)
        self.engine_details_label = QLabel(tr("create_analysis.lbl_engine_details"))
        engine_form.addRow(self.engine_details_label, self.engine_description_label)
        self._refresh_engine_description()

        # Buttons
        self.add_buttons(layout)

    def retranslateUi(self):
        self.setWindowTitle(tr("create_analysis.window_title"))
        if hasattr(self, "name_input"):
            self.name_input._field_label.setText(tr("create_analysis.lbl_name"))
        if hasattr(self, "description_input"):
            self.description_input._field_label.setText(tr("create_analysis.lbl_description"))
        if hasattr(self, "engine_group_box"):
            self.engine_group_box.setTitle(tr("create_analysis.group_first_task"))
        if hasattr(self, "engine_label"):
            self.engine_label.setText(tr("create_analysis.lbl_engine"))
        if hasattr(self, "engine_details_label"):
            self.engine_details_label.setText(tr("create_analysis.lbl_engine_details"))
        # Refresh engine combo items and description in the active language.
        if hasattr(self, "initial_engine_combo"):
            current_value = str(self.initial_engine_combo.currentData() or "")
            self.initial_engine_combo.blockSignals(True)
            self.initial_engine_combo.clear()
            for label, engine_type, description in get_simple_engine_choices():
                self.initial_engine_combo.addItem(label, engine_type.value)
                self.initial_engine_combo.setItemData(
                    self.initial_engine_combo.count() - 1,
                    description,
                    Qt.ItemDataRole.ToolTipRole,
                )
                if engine_type.value == current_value:
                    self.initial_engine_combo.setCurrentIndex(self.initial_engine_combo.count() - 1)
            self.initial_engine_combo.blockSignals(False)
            self._refresh_engine_description()

    def closeEvent(self, event):
        remove_listener(self.retranslateUi)
        super().closeEvent(event)

    def _refresh_engine_description(self, *_args):
        """Update helper text for the selected initial task engine."""
        engine_value = str(self.initial_engine_combo.currentData() or "").strip()
        self.engine_description_label.setText(engine_description_for_value(engine_value))

    def _selected_engine_type(self) -> Optional[EngineType]:
        engine_value = str(self.initial_engine_combo.currentData() or "").strip()
        for _label, engine_type, _description in get_simple_engine_choices():
            if engine_type.value == engine_value:
                return engine_type
        return None

    def get_analysis_request(self) -> Optional[Dict[str, Any]]:
        """
        Show dialog and return analysis plus initial task engine, or None if cancelled.

        Returns:
            Dict with ``analysis`` and ``engine_type`` keys when accepted.
        """
        if exec_dialog(self) == QDialog.DialogCode.Accepted:
            if not self.validate_required_field(self.name_input, tr("create_analysis.validation_name")):
                return self.get_analysis_request()

            engine_type = self._selected_engine_type()
            if engine_type is None:
                self.show_warning(tr("create_analysis.validation_title"), tr("create_analysis.validation_no_engine"))
                return self.get_analysis_request()

            analysis = Analysis(
                id=str(uuid.uuid4()),
                name=self.name_input.text().strip(),
                description=self.description_input.plain_text(),
            )
            analysis.metadata = apply_sidecar(
                analysis.metadata, self.description_input.html()
            )
            return {
                "analysis": analysis,
                "engine_type": engine_type,
            }

        return None

    def get_provenance(self) -> Optional[Analysis]:
        """
        Show dialog and return created Analysis or None if cancelled

        Returns:
            Analysis object if user clicked OK, None otherwise
        """
        request = self.get_analysis_request()
        return request["analysis"] if request else None
