"""Knowledge synthesis list command implementation."""

from typing import Optional

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.knowledge.synthesis.list.presenter import present_syntheses_list
from cli.infrastructure.command import async_command, authenticated_client


def knowledge_synthesis_list_command(
    collection: Optional[str] = typer.Option(
        None,
        "-C",
        "--collection",
        help="Filter by collection UUID",
    ),
    status: Optional[str] = typer.Option(
        None,
        "-s",
        "--status",
        help="Filter by status: accepted, queued, worker_assigned, processing, completed, failed",
    ),
    include_stale: bool = typer.Option(
        True,
        "--include-stale/--no-stale",
        help="Include stale syntheses (default: include)",
    ),
    limit: int = typer.Option(
        50,
        "-l",
        "--limit",
        min=1,
        max=100,
        help="Maximum results (1-100)",
    ),
    offset: int = typer.Option(
        0,
        "--offset",
        min=0,
        help="Pagination offset",
    ),
) -> None:
    """List syntheses for the organization.

    Supports filtering by collection, status, and staleness.
    Results are ordered by creation date (newest first).

    Examples:
        alloy knowledge synthesis list
        alloy knowledge synthesis list -C <collection-uuid>
        alloy knowledge synthesis list --status completed --no-stale
    """
    _execute_list_from_flags(
        collection=collection,
        status=status,
        include_stale=include_stale,
        limit=limit,
        offset=offset,
    )


def _execute_list_from_flags(
    collection: Optional[str],
    status: Optional[str],
    include_stale: bool,
    limit: int,
    offset: int,
) -> None:
    """Validate flags and execute list."""
    # Validate collection ID if provided
    collection_id: str | None = None
    if collection:
        validate_uuid(collection, "collection")
        collection_id = collection

    # Validate status if provided
    if status:
        valid_statuses = [
            "accepted",
            "queued",
            "worker_assigned",
            "processing",
            "completed",
            "failed",
        ]
        if status.lower() not in valid_statuses:
            raise typer.BadParameter(
                f"Invalid status '{status}'. Valid: {', '.join(valid_statuses)}"
            )
        status = status.lower()

    _execute_list(
        collection_id=collection_id,
        status=status,
        include_stale=include_stale,
        limit=limit,
        offset=offset,
    )


@async_command
async def _execute_list(
    collection_id: str | None,
    status: str | None,
    include_stale: bool,
    limit: int,
    offset: int,
) -> None:
    """Execute synthesis list."""
    async with authenticated_client() as (_config, client):
        response = await client.list_syntheses(
            collection_id=collection_id,
            status=status,
            include_stale=include_stale,
            limit=limit,
            offset=offset,
        )

    present_syntheses_list(response)
