"""list-sessions command — list recent sessions."""

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 get_store
from send_message.context import SendMessageContext


@app.command("list-sessions")
def list_sessions(
    ctx: typer.Context,
    limit: int = typer.Option(20, "--limit", "-l", help="Maximum number of sessions to list"),
) -> None:
    """List recent AI agent sessions."""
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SendMessageContext)
    console = app_ctx.console

    store = get_store()
    tool = app_ctx.tool

    if tool is not None:
        sessions = store.list_sessions(tool=tool, limit=limit)
    else:
        sessions = store.list_sessions(limit=limit)

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

    table = Table(title="Recent Sessions")
    table.add_column("Tool", style="cyan")
    table.add_column("Session ID", style="green")
    table.add_column("Title")
    table.add_column("Msgs", justify="right")
    table.add_column("Last Activity")
    table.add_column("Working Directory", style="dim")

    for s in sessions:
        session_id_display = s.session_id[:12] + "..." if len(s.session_id) > 15 else s.session_id
        table.add_row(
            s.tool,
            session_id_display,
            s.title,
            str(s.message_count),
            s.last_activity.strftime("%Y-%m-%d %H:%M"),
            s.working_directory,
        )

    console.print(table)
