#!/usr/bin/env bash

check-help-width() {
    local term_width
    term_width=$(tput cols 2>/dev/null || echo 80)

    echo "Terminal width: $term_width"
    echo

    local max_line_width=0
    local -a overflow_lines=()

    while IFS= read -r line; do
        local line_width=${#line}
        if (( line_width > max_line_width )); then
            max_line_width=$line_width
        fi
        # Skip table structure lines (separators, headers)
        [[ "$line" =~ ^\|[-]+.* ]] && continue
        [[ "$line" =~ ^\|[[:space:]]*Command[[:space:]]*\| ]] && continue
        # Skip group header rows where option and description are empty
        local -a fields
        IFS='|' read -ra fields <<< "$line"
        local opt_field="${fields[2]:-}"
        local desc_field="${fields[3]:-}"
        [[ -z "${opt_field// /}" && -z "${desc_field// /}" ]] && continue

        if (( line_width > term_width )); then
            overflow_lines+=("$line")
        fi
    done < <(help-table)

    echo "Max table line width: $max_line_width"

    if (( ${#overflow_lines[@]} > 0 )); then
        echo
        echo "Warning: The following commands exceed terminal width ($term_width):"
        for line in "${overflow_lines[@]}"; do
            printf '  %s\n' "$line"
        done
        return 1
    else
        echo "All commands fit within terminal width."
        return 0
    fi
}
chmw() {
    check-help-width "$@"
}
