from __future__ import annotations

import os
import sys

_ANSI_BY_COLOR = {
    "black": "30",
    "red": "31",
    "green": "32",
    "yellow": "33",
    "blue": "34",
    "magenta": "35",
    "cyan": "36",
    "white": "37",
}


def should_use_color() -> bool:
    if os.getenv("ONE_RUN_NO_COLOR") == "1":
        return False
    if os.getenv("ONE_RUN_FORCE_COLOR") == "1":
        return True
    return sys.stdout.isatty()


def colorize(value: str, color: str | None, *, enabled: bool) -> str:
    if not enabled or not color:
        return value
    code = _ANSI_BY_COLOR.get(color)
    if not code:
        return value
    return f"\x1b[{code}m{value}\x1b[0m"


def render_table(columns: list[str], rows: list[dict[str, str]]) -> list[str]:
    widths = {col: len(col) for col in columns}
    for row in rows:
        for col in columns:
            widths[col] = max(widths[col], len(row[col]))

    def _line(row: dict[str, str]) -> str:
        return "  ".join(row[col].ljust(widths[col]) for col in columns)

    header = "  ".join(col.ljust(widths[col]) for col in columns)
    return [header] + [_line(row) for row in rows]
