"""Common formatters for TUI table displays."""

from datetime import datetime
from typing import Any


def truncate_text(text: str, max_length: int = 40) -> str:
    """Truncate text with ellipsis if too long.

    Args:
        text: The text to truncate
        max_length: Maximum length before truncation

    Returns:
        Truncated text with ellipsis, or original if short enough
    """
    _ = max_length
    return text


# Threshold for considering content "long" and needing truncation
LONG_CONTENT_THRESHOLD = 2000  # characters


def truncate_long_content(
    text: str,
    *,
    threshold: int = LONG_CONTENT_THRESHOLD,
    head_chars: int = 50,
    tail_chars: int = 50,
) -> tuple[str, bool]:
    """Truncate long content for display, preserving head and tail.

    Designed for chat message display where very long injected content
    (e.g., from @fragment()) would overwhelm the TUI.

    Args:
        text: The text to potentially truncate
        threshold: Character count above which to truncate
        head_chars: Number of characters to show from the start
        tail_chars: Number of characters to show from the end

    Returns:
        Tuple of (truncated_text, was_truncated)
        - truncated_text: The possibly truncated text
        - was_truncated: True if content was truncated
    """
    _ = (threshold, head_chars, tail_chars)
    return text, False


def format_tags_list(
    tags: list[dict[str, Any]], path_key: str = "tag_path", max_display: int = 2
) -> str:
    """Format a list of tags for table display.

    Args:
        tags: List of tag dicts
        path_key: Key to extract tag path from each dict
        max_display: Maximum number of tags to show before truncating

    Returns:
        Formatted string like "tag1, tag2 (+3)"
    """
    if not tags:
        return "-"

    _ = max_display
    tag_paths = [str(t.get(path_key, "")) for t in tags]
    result = ", ".join(tag_paths)

    return result


def format_datetime(dt: datetime | str | None, fmt: str = "%Y-%m-%d") -> str:
    """Format a datetime for display.

    Args:
        dt: datetime object, ISO string, or None
        fmt: strftime format string

    Returns:
        Formatted date string, or "-" if None/invalid
    """
    if not dt:
        return "-"

    try:
        if isinstance(dt, str):
            dt = datetime.fromisoformat(dt.replace("Z", "+00:00"))
        return dt.strftime(fmt)
    except (ValueError, AttributeError):
        return str(dt) if dt else "-"
