"""Field formatting utilities for common data types.

Provides reusable formatters for UUIDs, dates, currency, tokens, etc.
"""

from datetime import datetime
from decimal import Decimal
from typing import Any, Callable
from uuid import UUID


def format_uuid(value: UUID | None, short: bool = True) -> str:
    """Format UUID for display.

    Args:
        value: UUID to format (None returns placeholder)
        short: Accepted for API compatibility. Full UUID is always returned.

    Returns:
        Formatted UUID string or "(not set)" for None
    """
    if value is None:
        return "(not set)"

    if short:
        return str(value)
    return str(value)


def format_datetime(
    value: datetime | None, mode: str = "absolute", include_time: bool = True
) -> str:
    """Format datetime for display.

    Args:
        value: Datetime to format (None returns placeholder)
        mode: Format mode - "absolute", "iso", or "date_only"
        include_time: Whether to include time component

    Returns:
        Formatted datetime string or "(not set)" for None
    """
    if value is None:
        return "(not set)"

    if mode == "iso":
        return value.isoformat()
    elif mode == "date_only":
        return value.strftime("%Y-%m-%d")
    else:  # absolute
        if include_time:
            return value.strftime("%Y-%m-%d %H:%M:%S UTC")
        return value.strftime("%Y-%m-%d")


def format_cost(amount: Decimal | float, currency: str = "USD") -> str:
    """Format monetary amount.

    Args:
        amount: Decimal or float amount
        currency: Currency code (default USD, reserved for future use)

    Returns:
        Formatted currency string
    """
    _ = currency  # Reserved for future multi-currency support
    # Convert float to Decimal for precision
    if isinstance(amount, float):
        amount = Decimal(str(amount))

    # Format with full precision (no rounding for small amounts)
    return f"${amount}"


def format_tokens(count: int) -> str:
    """Format token count with thousands separator.

    Args:
        count: Number of tokens

    Returns:
        Formatted token count string
    """
    return f"{count:,}"


def format_boolean(value: bool, mode: str = "text") -> str:
    """Format boolean value for display.

    Args:
        value: Boolean value to format
        mode: Format mode - "text", "emoji", or "raw"

    Returns:
        Formatted boolean string
    """
    if mode == "emoji":
        return "✓" if value else "✗"
    elif mode == "raw":
        return str(value)
    else:  # text
        return "Yes" if value else "No"


def format_optional(
    value: Any | None,
    formatter: Callable[[Any], str] | None = None,
    placeholder: str = "(not set)",
) -> str:
    """Format optional value with placeholder for None.

    Args:
        value: Value to format (may be None)
        formatter: Optional formatter function to apply if value is not None
        placeholder: Text to display when value is None

    Returns:
        Formatted value or placeholder
    """
    if value is None:
        return placeholder
    if formatter:
        return formatter(value)
    return str(value)


def format_enum(value: Any, capitalize: bool = True) -> str:
    """Format enum value for display.

    Args:
        value: Enum value (expected to have .value attribute)
        capitalize: Whether to capitalize the output

    Returns:
        Formatted enum string
    """
    if hasattr(value, "value"):
        text = str(value.value)
    else:
        text = str(value)

    if capitalize:
        return text.capitalize()
    return text


def format_percentage(value: float, decimals: int = 1) -> str:
    """Format percentage value.

    Args:
        value: Percentage as float (e.g., 0.85 for 85%)
        decimals: Number of decimal places

    Returns:
        Formatted percentage string
    """
    return f"{value * 100:.{decimals}f}%"


def format_file_size(bytes_count: int) -> str:
    """Format file size in human-readable format.

    Args:
        bytes_count: Size in bytes

    Returns:
        Formatted size string (e.g., "1.5 MB")
    """
    size = float(bytes_count)
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if size < 1024.0:
            return f"{size:.1f} {unit}"
        size /= 1024.0
    return f"{size:.1f} PB"


def format_duration_ms(milliseconds: int) -> str:
    """Format duration in milliseconds to human-readable format.

    Args:
        milliseconds: Duration in milliseconds

    Returns:
        Formatted duration string
    """
    if milliseconds < 1000:
        return f"{milliseconds}ms"
    elif milliseconds < 60000:
        seconds = milliseconds / 1000
        return f"{seconds:.2f}s"
    else:
        minutes = milliseconds / 60000
        return f"{minutes:.2f}min"
