"""
Formatting utilities for groknroll.

Provides human-readable formatting for durations, sizes, and other values.
"""


def format_duration(seconds: int | float) -> str:
    """
    Format a duration in seconds to a human-readable string.

    Args:
        seconds: Duration in seconds

    Returns:
        Human-readable duration string (e.g., "1h 30m", "~2 days")

    Examples:
        >>> format_duration(90)
        '1m 30s'
        >>> format_duration(3661)
        '1h 1m'
        >>> format_duration(86400)
        '~1 day'
    """
    if seconds <= 0:
        return ""

    seconds = int(seconds)

    # Constants
    MINUTE = 60
    HOUR = 60 * MINUTE
    DAY = 24 * HOUR
    WEEK = 7 * DAY

    # Weeks
    if seconds >= WEEK:
        weeks = seconds // WEEK
        return f"~{weeks} week" if weeks == 1 else f"~{weeks} weeks"

    # Days
    if seconds >= DAY:
        days = seconds // DAY
        return f"~{days} day" if days == 1 else f"~{days} days"

    # Hours
    if seconds >= HOUR:
        hours = seconds // HOUR
        remaining_minutes = (seconds % HOUR) // MINUTE
        if remaining_minutes > 0:
            return f"{hours}h {remaining_minutes}m"
        return f"{hours}h"

    # Minutes
    if seconds >= MINUTE:
        minutes = seconds // MINUTE
        remaining_seconds = seconds % MINUTE
        if remaining_seconds > 0:
            return f"{minutes}m {remaining_seconds}s"
        return f"{minutes}m"

    # Seconds
    return f"{seconds}s"


def format_bytes(num_bytes: int) -> str:
    """
    Format a byte count to a human-readable string.

    Args:
        num_bytes: Number of bytes

    Returns:
        Human-readable size string (e.g., "1.5 KB", "2.3 MB")

    Examples:
        >>> format_bytes(1024)
        '1.0 KB'
        >>> format_bytes(1536)
        '1.5 KB'
    """
    if num_bytes < 0:
        return "0 B"

    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if abs(num_bytes) < 1024:
            return f"{num_bytes:.1f} {unit}" if unit != "B" else f"{num_bytes} B"
        num_bytes /= 1024

    return f"{num_bytes:.1f} PB"


def format_count(count: int, singular: str, plural: str | None = None) -> str:
    """
    Format a count with proper singular/plural form.

    Args:
        count: The count value
        singular: Singular form of the word
        plural: Plural form (defaults to singular + 's')

    Returns:
        Formatted count string

    Examples:
        >>> format_count(1, "file")
        '1 file'
        >>> format_count(5, "file")
        '5 files'
    """
    if plural is None:
        plural = singular + "s"

    return f"{count} {singular}" if count == 1 else f"{count} {plural}"
