"""Builder for switch timing and combo-selection settings section."""

from __future__ import annotations

from PyQt6.QtWidgets import (
    QButtonGroup,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QVBoxLayout,
)

def build_switch_group(owner) -> QGroupBox:
    """Create switch timing field and two explicit combo-selection modes."""
    group = QGroupBox("Switches")
    layout = QVBoxLayout(group)
    layout.setSpacing(8)

    switch_defaults = owner._gui_defaults.switches

    global_form = QFormLayout()
    global_form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
    owner._settling_ms = QLineEdit(str(owner._defaults_config.runtime.settling_ms))
    global_form.addRow("Settling ms", owner._settling_ms)
    layout.addLayout(global_form)

    owner._combos_text = QLineEdit(str(switch_defaults.combos_text))
    owner._combos_text.setPlaceholderText("empty = full matrix, or input:output,input:output")
    owner._run_combos_select_button = QPushButton("Select")
    owner._run_combos_select_button.setCheckable(True)

    combos_row = QHBoxLayout()
    combos_row.setSpacing(8)
    combos_row.addWidget(QLabel("Run combos"))
    combos_row.addWidget(owner._combos_text, stretch=1)
    combos_row.addWidget(owner._run_combos_select_button)
    layout.addLayout(combos_row)

    owner._single_combo_output = QLineEdit(str(switch_defaults.single_output))
    owner._single_combo_output.setPlaceholderText("0")
    owner._single_combo_input = QLineEdit(str(switch_defaults.single_input))
    owner._single_combo_input.setPlaceholderText("0")
    owner._single_combo_select_button = QPushButton("Select")
    owner._single_combo_select_button.setCheckable(True)

    single_row = QHBoxLayout()
    single_row.setSpacing(8)
    single_row.addWidget(QLabel("Single combo"))
    single_row.addWidget(QLabel("Input"))
    single_row.addWidget(owner._single_combo_input)
    single_row.addWidget(QLabel("Output"))
    single_row.addWidget(owner._single_combo_output)
    single_row.addWidget(owner._single_combo_select_button)
    layout.addLayout(single_row)

    owner._combo_select_group = QButtonGroup(group)
    owner._combo_select_group.setExclusive(True)
    owner._combo_select_group.addButton(owner._run_combos_select_button)
    owner._combo_select_group.addButton(owner._single_combo_select_button)

    owner._run_combos_select_button.clicked.connect(lambda: owner._set_combo_selection_mode("text"))
    owner._single_combo_select_button.clicked.connect(lambda: owner._set_combo_selection_mode("single"))
    owner._single_combo_output.editingFinished.connect(owner._on_processing_live_settings_changed)
    owner._single_combo_input.editingFinished.connect(owner._on_processing_live_settings_changed)
    owner._set_combo_selection_mode(str(switch_defaults.combo_mode))

    return group
