"""
ASCII table formatting — no external dependencies.
"""

from __future__ import annotations

from typing import Any


def table(rows: list[dict[str, Any]], columns: list[tuple[str, str, int]]) -> str:
    """
    Render a simple ASCII table.

    columns: list of (key, header_label, min_width)
    """
    if not rows:
        return "  (no results)"

    # Compute column widths
    widths: list[int] = []
    for key, label, min_w in columns:
        col_max = max(len(str(row.get(key, ""))) for row in rows)
        widths.append(max(min_w, len(label), col_max))

    # Header
    header_parts = []
    for (_, label, _), w in zip(columns, widths):
        header_parts.append(label.ljust(w))
    header = "  ".join(header_parts)

    # Separator
    sep = "  ".join("-" * w for w in widths)

    # Rows
    lines = [header, sep]
    for row in rows:
        parts = []
        for (key, _, _), w in zip(columns, widths):
            val = str(row.get(key, ""))
            parts.append(val.ljust(w))
        lines.append("  ".join(parts))

    return "\n".join(lines)


def kv(pairs: list[tuple[str, Any]], indent: int = 2) -> str:
    """Render key-value pairs, right-aligned keys."""
    if not pairs:
        return ""
    max_key = max(len(k) for k, _ in pairs)
    lines = []
    for k, v in pairs:
        lines.append(f"{' ' * indent}{k.rjust(max_key)}  {v}")
    return "\n".join(lines)
