"""使用 rich 格式化终端输出"""

import json

from rich.console import Console
from rich.table import Table
from rich import print_json as rich_print_json

console = Console()


def print_table(data, columns: list = None):
    """以 rich 表格形式打印数据列表"""
    if not data:
        console.print("[yellow]No items.[/yellow]")
        return

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

    # 确定列名（未指定时取所有条目 key 的并集，保持首次出现顺序）
    if not columns:
        seen = set()
        columns = []
        for item in data:
            for k in item.keys():
                if k not in seen:
                    columns.append(k)
                    seen.add(k)

    table = Table(show_header=True, header_style="bold cyan")
    for col in columns:
        table.add_column(col)

    for item in data:
        row = []
        for col in columns:
            val = item.get(col, "")
            if isinstance(val, (dict, list)):
                val = json.dumps(val, ensure_ascii=False)
            elif val is None:
                val = ""
            else:
                val = str(val)
            row.append(val)
        table.add_row(*row)

    console.print(table)


def print_json(data):
    """以高亮 JSON 格式打印数据"""
    rich_print_json(json.dumps(data, ensure_ascii=False))
