"""Template version create command implementation."""

from pathlib import Path
from typing import Optional

import typer

from cli.commands.flag_utils import parse_tags, require_one_of
from cli.commands.templates.version.presenter import present_version_create_success
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.templates import CreateTemplateVersionRequest


def templates_version_command(
    template: str = typer.Argument(
        ...,
        help="Template name or UUID",
    ),
    content_file: Optional[Path] = typer.Option(
        None,
        "-f",
        "--file",
        help="Read content from file",
        exists=True,
        readable=True,
    ),
    content: Optional[str] = typer.Option(
        None,
        "-c",
        "--content",
        help="Inline content",
    ),
    tags: Optional[str] = typer.Option(
        None,
        "-t",
        "--tags",
        help="Replace tags (comma-separated)",
    ),
    clear_tags: bool = typer.Option(
        False,
        "--clear-tags",
        help="Remove all tags",
    ),
) -> None:
    """Create a new version of a template.

    Examples:
        alloy templates version my-template -c "Updated content"
        alloy templates version my-template -f updated.jinja2
        alloy templates version my-template -c "New content" -t "email,v2"
        alloy templates version my-template -c "New content" --clear-tags
    """
    require_one_of(("--file", content_file), ("--content", content))

    _execute_version_from_flags(
        template_identifier=template,
        content_file=content_file,
        content=content,
        tags=tags,
        clear_tags=clear_tags,
    )


def _execute_version_from_flags(
    template_identifier: str,
    content_file: Optional[Path],
    content: Optional[str],
    tags: Optional[str],
    clear_tags: bool,
) -> None:
    """Build and execute version creation from command flags."""
    # Get content from file or inline
    if content_file:
        template_content = content_file.read_text()
    else:
        template_content = content or ""

    if not template_content.strip():
        raise typer.BadParameter("Template content cannot be empty")

    # Parse tags
    tag_paths: list[str] | None = None
    if clear_tags:
        tag_paths = []
    elif tags:
        tag_paths = parse_tags(tags)

    # Build request
    request = CreateTemplateVersionRequest(
        content=template_content,
        tag_paths=tag_paths,
    )

    _resolve_and_create_version(template_identifier, request)


@async_command
async def _resolve_and_create_version(
    template_identifier: str, request: CreateTemplateVersionRequest
) -> None:
    """Resolve template identifier and create version."""
    from alloy_runtime_sdk.exceptions.errors import NotFoundError

    async with authenticated_client() as (_config, client):
        try:
            template_data = await client.get_template(template_identifier)
        except NotFoundError:
            raise typer.BadParameter(
                f"Template '{template_identifier}' not found. Use 'alloy templates list' to see available templates."
            )

        response = await client.create_template_version(
            template_data.template.id, request
        )

    present_version_create_success(response)
