"""通用工具函数"""
import json
from datetime import datetime, date
from typing import Any

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

console = Console()
err_console = Console(stderr=True, style="bold red")


def format_size(size_bytes: int) -> str:
    """将字节数转换为可读的文件大小字符串"""
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if size_bytes < 1024:
            return f"{size_bytes:.1f} {unit}"
        size_bytes /= 1024
    return f"{size_bytes:.1f} PB"


def format_datetime(dt) -> str:
    """格式化日期时间对象为字符串"""
    if dt is None:
        return "-"
    if isinstance(dt, (datetime, date)):
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    return str(dt)


class DateTimeEncoder(json.JSONEncoder):
    """支持 datetime 序列化的 JSON encoder"""

    def default(self, obj: Any) -> Any:
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        return super().default(obj)


def print_json(data: Any) -> None:
    """以 JSON 格式打印数据"""
    console.print_json(json.dumps(data, cls=DateTimeEncoder, ensure_ascii=False))


def handle_error(e: Exception, operation: str = "") -> None:
    """统一处理并打印错误信息"""
    from botocore.exceptions import ClientError

    if isinstance(e, ClientError):
        code = e.response["Error"]["Code"]
        message = e.response["Error"]["Message"]
        prefix = f"[{operation}] " if operation else ""
        err_console.print(f"{prefix}AWS 错误 ({code}): {message}")
    else:
        err_console.print(f"错误: {e}")
    raise SystemExit(1)
