"""Shared layout helpers for section builders."""

from __future__ import annotations

from typing import TypeAlias

from PyQt6.QtWidgets import QFormLayout, QHBoxLayout, QWidget


FormLabel: TypeAlias = str | QWidget
FormRow: TypeAlias = QWidget | tuple[FormLabel, QWidget]


def build_two_column_form_widget(
    parent: QWidget,
    rows: list[FormRow],
    *,
    split_index: int | None = None,
) -> QWidget:
    """Build one widget containing two side-by-side form columns."""
    panel = QWidget(parent)
    panel_layout = QHBoxLayout(panel)
    panel_layout.setContentsMargins(0, 0, 0, 0)
    panel_layout.setSpacing(12)

    left_column = QWidget(panel)
    left_form = _create_form_layout(left_column)
    right_column = QWidget(panel)
    right_form = _create_form_layout(right_column)

    panel_layout.addWidget(left_column, stretch=1)
    panel_layout.addWidget(right_column, stretch=1)

    actual_split_index = (len(rows) + 1) // 2 if split_index is None else split_index
    actual_split_index = max(0, min(actual_split_index, len(rows)))

    for row in rows[:actual_split_index]:
        _add_form_row(left_form, row)
    for row in rows[actual_split_index:]:
        _add_form_row(right_form, row)
    return panel


def _create_form_layout(parent: QWidget) -> QFormLayout:
    """Create a compact growing form layout for one column."""
    form = QFormLayout(parent)
    form.setContentsMargins(0, 0, 0, 0)
    form.setHorizontalSpacing(10)
    form.setVerticalSpacing(6)
    form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
    return form


def _add_form_row(form: QFormLayout, row: FormRow) -> None:
    """Append one form row, with or without an explicit label."""
    if isinstance(row, tuple):
        label, field = row
        form.addRow(label, field)
        return
    form.addRow(row)
