"""Templates list command implementation."""

from typing import Optional

import typer

from cli.commands.flag_utils import validate_template_content_type, validate_visibility
from cli.commands.templates.list.presenter import present_templates_list
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.enums.template_enums import (
    TemplateContentType,
    TemplateVisibility,
)


def templates_list_command(
    search: Optional[str] = typer.Option(
        None,
        "-s",
        "--search",
        help="Fuzzy search terms",
    ),
    content_type: Optional[str] = typer.Option(
        None,
        "--type",
        help="Filter by type: system_instruction, user_message, fragment",
    ),
    visibility: Optional[str] = typer.Option(
        None,
        "-V",
        "--visibility",
        help="Filter by: private, organization, public",
    ),
    tag_path: Optional[str] = typer.Option(
        None,
        "-t",
        "--tag",
        help="Filter by tag pattern (e.g., '*.email.*')",
    ),
    limit: int = typer.Option(
        50,
        "-l",
        "--limit",
        min=1,
        max=100,
        help="Max results",
    ),
    cursor: Optional[str] = typer.Option(
        None,
        "--cursor",
        help="Pagination cursor",
    ),
) -> None:
    """List templates.

    Examples:
        alloy templates list
        alloy templates list -s "email newsletter"
        alloy templates list --type system_instruction
        alloy templates list -V organization -t "*.email.*"
        alloy templates list -l 20
    """
    # Parse and validate enums
    content_type_enum: Optional[TemplateContentType] = None
    if content_type:
        content_type_enum = validate_template_content_type(content_type)

    visibility_enum: Optional[TemplateVisibility] = None
    if visibility:
        visibility_enum = validate_visibility(visibility)

    _execute_list(
        search=search,
        content_type=content_type_enum,
        visibility=visibility_enum,
        tag_path=tag_path,
        limit=limit,
        cursor=cursor,
    )


@async_command
async def _execute_list(
    search: Optional[str],
    content_type: Optional[TemplateContentType],
    visibility: Optional[TemplateVisibility],
    tag_path: Optional[str],
    limit: int,
    cursor: Optional[str],
) -> None:
    """Execute list templates operation."""
    async with authenticated_client() as (_config, client):
        response = await client.list_templates(
            search=search,
            content_type=content_type,
            visibility=visibility,
            tag_path=tag_path,
            limit=limit,
            cursor=cursor,
        )

    present_templates_list(response)
