"""Knowledge collection cluster command implementation."""

import typer

from cli.commands.knowledge.collections.cluster.presenter import (
    present_cluster_status,
    present_cluster_triggered,
)
from cli.infrastructure.command import async_command, authenticated_client


def knowledge_collections_cluster_command(
    collection: str = typer.Argument(
        ...,
        help="Collection name or UUID",
    ),
    wait: bool = typer.Option(
        False,
        "--wait",
        help="Wait for clustering to complete before returning",
    ),
    timeout: float = typer.Option(
        300.0,
        "--timeout",
        help="Maximum seconds to wait when using --wait (default: 300)",
    ),
) -> None:
    """Trigger clustering for a knowledge collection.

    Queues an asynchronous clustering run. Use --wait to block until complete.

    Examples:
        alloy knowledge collections cluster my-collection
        alloy knowledge collections cluster 550e8400-e29b-41d4-a716-446655440000 --wait
        alloy knowledge collections cluster my-collection --wait --timeout 600
    """
    _execute_cluster(
        collection_identifier=collection,
        wait=wait,
        timeout=timeout,
    )


@async_command
async def _execute_cluster(
    collection_identifier: str,
    wait: bool,
    timeout: float,
) -> None:
    """Execute cluster operation."""
    async with authenticated_client() as (_config, client):
        response = await client.trigger_collection_clustering(collection_identifier)

    present_cluster_triggered(response)

    if wait:
        async with authenticated_client() as (_config, client):
            status = await client.wait_for_collection_clustering(
                collection_identifier,
                task_id=response.task_id,
                timeout=timeout,
            )

        present_cluster_status(status)
