"""Knowledge documents list command implementation."""

import typer
from typing import cast

from alloy_runtime_types.dtos.knowledge import ListDocumentsRequest, ProcessingStatus

from cli.commands.knowledge.documents.list.presenter import present_documents_list
from cli.infrastructure.command import async_command, authenticated_client


def knowledge_documents_list_command(
    collection: str | None = typer.Option(
        None,
        "-C",
        "--collection",
        help="Filter by collection ID or name",
    ),
    status: str | None = typer.Option(
        None,
        "-s",
        "--status",
        help="Filter by status: queued|processing|completed|failed|duplicate|filtered",
    ),
    external_id: str | None = typer.Option(
        None,
        "--external-id",
        help="Filter by exact external_id match",
    ),
    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",
    ),
) -> None:
    """List documents in the knowledge base.

    Examples:
        alloy knowledge documents list
        alloy knowledge documents list -C my-collection
        alloy knowledge documents list -s completed -l 20
        alloy knowledge documents list --external-id crm-123
        alloy knowledge documents list -s duplicate
        alloy knowledge documents list -s filtered
        alloy knowledge documents list --status failed
    """
    _execute_list(
        collection_id=collection,
        processing_status=status,
        external_id=external_id,
        limit=limit,
        offset=offset,
    )


@async_command
async def _execute_list(
    collection_id: str | None,
    processing_status: str | None,
    external_id: str | None,
    limit: int,
    offset: int,
) -> None:
    """Execute list documents operation."""
    request = ListDocumentsRequest(
        collection_id=collection_id,
        processing_status=cast(ProcessingStatus | None, processing_status),
        external_id=external_id,
        limit=limit,
        offset=offset,
    )
    async with authenticated_client() as (_config, client):
        response = await client.list_documents(request)

    present_documents_list(response)
