from __future__ import annotations

from io import StringIO
from typing import Any

from rich.console import Console
from rich.table import Table


def _normalize_rows(data: Any) -> list[dict]:
    if isinstance(data, list):
        rows = []
        for item in data:
            if isinstance(item, dict):
                rows.append(item)
            else:
                rows.append({"value": item})
        return rows

    if isinstance(data, dict):
        return [data]

    return [{"value": data}]


def format_table(data: Any) -> str:
    rows = _normalize_rows(data)
    columns = sorted({key for row in rows for key in row.keys()})
    table = Table(show_header=True, header_style="bold cyan")
    for col in columns:
        table.add_column(col, overflow="fold")

    for row in rows:
        table.add_row(*[str(row.get(col, "")) for col in columns])

    buffer = StringIO()
    console = Console(file=buffer, force_terminal=False, color_system=None)
    console.print(table)
    return buffer.getvalue().rstrip()
