"""Session messages list command implementation."""

from typing import Optional
from uuid import UUID

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.sessions.messages.presenter import present_messages_list
from cli.infrastructure.command import async_command, authenticated_client


def sessions_messages_command(
    session_id: str = typer.Argument(
        ...,
        help="Session UUID",
    ),
    role: Optional[str] = typer.Option(
        None,
        "--role",
        help="Filter by role (user, assistant, system, tool)",
    ),
    limit: int = typer.Option(
        50,
        "-l",
        "--limit",
        min=1,
        max=100,
        help="Max results",
    ),
    offset: int = typer.Option(
        0,
        "--offset",
        min=0,
        help="Skip N results",
    ),
    order: str = typer.Option(
        "asc",
        "--order",
        help="Sort order (asc or desc)",
    ),
) -> None:
    """List messages in a chat session.

    Examples:
        alloy sessions messages 123e4567-89ab...
        alloy sessions messages 123e4567-89ab... --role assistant
        alloy sessions messages 123e4567-89ab... --order desc -l 10
    """
    session_uuid = validate_uuid(session_id, "session")
    _execute_list(
        session_id=session_uuid,
        role=role,
        limit=limit,
        offset=offset,
        order=order,
    )


@async_command
async def _execute_list(
    session_id: UUID,
    role: Optional[str],
    limit: int,
    offset: int,
    order: str,
) -> None:
    """Execute list messages operation."""
    async with authenticated_client() as (_config, client):
        response = await client.list_session_messages(
            session_id,
            role=role,
            limit=limit,
            offset=offset,
            order=order,
        )

    present_messages_list(response)
