__version__ = "0.1.0"
__author__ = "Tabledevil <tabledevil@gmail.com>"

from visidata import Sheet, BaseSheet, vd


@Sheet.api
def hide_empty_and_superfluous_cols(sheet):
    """
    Given a sheet, hides columns that are empty or superfluous (contain the same
    value in every row).
    """
    counter = 0
    # Iterate over a snapshot; hiding columns mutates sheet.visibleCols.
    for col in list(sheet.visibleCols):
        if not col.width or col.width <= 0:
            continue

        # Single pass over rows: track emptiness and distinct non-empty values.
        all_empty = True
        nonempty_vals = set()
        for row in sheet.rows:
            v = col.getValue(row)
            if v in (None, "", "null"):
                continue
            all_empty = False
            nonempty_vals.add(str(v))
            if len(nonempty_vals) > 1:
                break

        if all_empty or len(nonempty_vals) == 1:
            col.width = 0
            counter += 1

    if counter:
        vd.status(f"Hid {counter} empty/superfluous columns.")
    else:
        vd.status("No empty/superfluous columns to hide.")

Sheet.addCommand(
    None,
    "tke-hidecol",
    "sheet.hide_empty_and_superfluous_cols()",
    helpstr="Hide columns that are empty or have the same value in every row.",
)

# Make the command discoverable in the top menu bar (no default keybinding).
vd.addMenuItem("Column", "Hide", "empty/superfluous columns", "tke-hidecol")
