"""Convert a 2D list of cells to a markdown table with column alignment."""


def format_table_to_markdown(rows: list[list[str]], has_header: bool = True) -> str:
    """Convert a 2D list of cells to a markdown table.

    Args:
        rows: 2D list where each inner list is a row of cell strings.
        has_header: If True, the first row is treated as the header row.

    Returns:
        str: Markdown table string. Returns empty string for empty input.
    """
    if not rows:
        return ""

    def escape_cell(cell: str) -> str:
        return str(cell).replace("|", "\\|")

    # Determine column count from widest row
    col_count = max(len(row) for row in rows)

    # Pad rows to same column count
    padded = [row + [""] * (col_count - len(row)) for row in rows]

    # Escape pipe characters in all cells
    escaped = [[escape_cell(cell) for cell in row] for row in padded]

    # Calculate max width per column
    col_widths = [
        max(len(escaped[r][c]) for r in range(len(escaped)))
        for c in range(col_count)
    ]
    col_widths = [max(w, 3) for w in col_widths]  # minimum width of 3 for separator

    def format_row(row: list[str]) -> str:
        cells = [cell.ljust(col_widths[i]) for i, cell in enumerate(row)]
        return "| " + " | ".join(cells) + " |"

    lines = []

    if has_header and len(escaped) >= 1:
        lines.append(format_row(escaped[0]))
        separator = "| " + " | ".join("-" * col_widths[i] for i in range(col_count)) + " |"
        lines.append(separator)
        for row in escaped[1:]:
            lines.append(format_row(row))
    else:
        for row in escaped:
            lines.append(format_row(row))

    return "\n".join(lines)
