"""list-messages command — list messages in a session."""

import typer
from rich.table import Table

from cli_framework import get_context
from send_message.cli import app
from send_message.commands._helpers import resolve_tool_and_session, show_available_sessions
from send_message.context import SendMessageContext
from session_store.errors import SessionNotFoundError


@app.command("list-messages")
def list_messages(
    ctx: typer.Context,
    limit: int = typer.Option(20, "--limit", "-l", help="Maximum number of messages to list"),
    all: bool = typer.Option(
        False, "--all", "-a", help="List all messages, not just assistant messages"
    ),
) -> None:
    """List messages in a session."""
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SendMessageContext)
    console = app_ctx.console

    tool, session_id, store = resolve_tool_and_session(ctx)

    try:
        session = store.get_session(session_id, tool=tool)
    except SessionNotFoundError:
        console.print(f"[red]Error:[/red] Session not found: {session_id}")
        show_available_sessions(console, store, tool=tool)
        raise typer.Exit(1) from None

    if all:
        messages = session.messages
    else:
        from session_store import MessageSelector

        selector = MessageSelector()
        messages = selector.filter_assistant(session.messages)

    if not messages:
        console.print("[dim]No messages found[/dim]")
        return

    table = Table(title=f"Messages in {session.title}")
    table.add_column("#", justify="right", style="cyan")
    table.add_column("Role", style="green")
    table.add_column("Content (truncated)")
    table.add_column("Created", style="dim")

    for i, msg in enumerate(messages[:limit], 1):
        content_preview = msg.content[:60].replace("\n", " ")
        if len(msg.content) > 60:
            content_preview += "..."
        table.add_row(
            str(i),
            msg.role,
            content_preview,
            msg.created_at.strftime("%Y-%m-%d %H:%M"),
        )

    console.print(table)
