"""
Text formatters for Slack data (LLM-friendly output).
"""

from .message import MessageList, ChannelList, UserList, Message, Channel


def format_message(msg: Message, users: dict[str, str] | None = None) -> str:
    """Format a single message."""
    user_display = msg.user
    if users and msg.user and msg.user in users:
        user_display = users[msg.user]

    time_str = msg.timestamp.strftime("%Y-%m-%d %H:%M") if msg.timestamp else msg.ts
    thread_info = f" [thread: {msg.reply_count} replies]" if msg.reply_count > 0 else ""

    return f"[{time_str}] {user_display}: {msg.text}{thread_info}"


def format_message_list(data: MessageList, users: dict[str, str] | None = None) -> str:
    """Format message list for text output."""
    lines = [f"Channel: {data.channel_id}", f"Messages: {len(data.messages)}", ""]

    for msg in data.messages:
        lines.append(format_message(msg, users))

    if data.has_more:
        lines.append("\n[More messages available...]")

    return "\n".join(lines)


def format_channel(ch: Channel) -> str:
    """Format a single channel."""
    flags = []
    if ch.is_private:
        flags.append("private")
    if ch.is_archived:
        flags.append("archived")
    if ch.is_member:
        flags.append("member")

    flag_str = f" ({', '.join(flags)})" if flags else ""
    members_str = f" [{ch.num_members} members]" if ch.num_members else ""

    return f"#{ch.name} ({ch.id}){flag_str}{members_str}"


def format_channel_list(data: ChannelList) -> str:
    """Format channel list for text output."""
    lines = [f"Channels: {data.total}", ""]

    for ch in data.channels:
        lines.append(format_channel(ch))
        if ch.purpose:
            lines.append(f"  Purpose: {ch.purpose}")

    return "\n".join(lines)


def format_user_list(data: UserList) -> str:
    """Format user list for text output."""
    lines = [f"Users: {data.total}", ""]

    for u in data.users:
        bot_flag = " [bot]" if u.is_bot else ""
        display = u.display_name or u.real_name or u.name
        lines.append(f"@{u.name} ({u.id}) - {display}{bot_flag}")

    return "\n".join(lines)
