"""Builder for stable GPR configuration section."""

from __future__ import annotations

from PyQt6.QtWidgets import QComboBox, QDoubleSpinBox, QFormLayout, QGroupBox, QPlainTextEdit


def _format_tx_geometry(owner) -> str:
    """Render Tx geometry defaults into editable line-based text."""
    return "\n".join(
        f"{int(entry.output_pos)} {float(entry.x_m):g}"
        for entry in owner._defaults_config.gpr.tx_geometry
    )


def _format_rx_geometry(owner) -> str:
    """Render Rx geometry defaults into editable line-based text."""
    return "\n".join(
        f"{int(entry.input_pos)} {float(entry.x_m):g}"
        for entry in owner._defaults_config.gpr.rx_geometry
    )


def build_gpr_config_group(owner) -> QGroupBox:
    """Create stable GPR config controls backed by run_config.json."""
    group = QGroupBox("GPR Config")
    form = QFormLayout(group)
    form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
    defaults = owner._defaults_config.gpr

    owner._gpr_config_mode = QComboBox()
    owner._gpr_config_mode.addItems(["point", "extended"])
    owner._set_combo_current_text(owner._gpr_config_mode, defaults.mode)

    owner._gpr_relative_permittivity = QDoubleSpinBox()
    owner._gpr_relative_permittivity.setDecimals(4)
    owner._gpr_relative_permittivity.setRange(0.0001, 1000.0)
    owner._gpr_relative_permittivity.setSingleStep(0.05)
    owner._gpr_relative_permittivity.setValue(float(defaults.relative_permittivity))

    owner._gpr_tx_geometry_input = QPlainTextEdit(_format_tx_geometry(owner))
    owner._gpr_tx_geometry_input.setPlaceholderText("output_pos x_m")
    owner._gpr_tx_geometry_input.setMinimumHeight(88)

    owner._gpr_rx_geometry_input = QPlainTextEdit(_format_rx_geometry(owner))
    owner._gpr_rx_geometry_input.setPlaceholderText("input_pos x_m")
    owner._gpr_rx_geometry_input.setMinimumHeight(120)

    form.addRow("Mode", owner._gpr_config_mode)
    form.addRow("Relative Permittivity", owner._gpr_relative_permittivity)
    form.addRow("Tx Geometry", owner._gpr_tx_geometry_input)
    form.addRow("Rx Geometry", owner._gpr_rx_geometry_input)
    return group
