"""Template render command implementation."""

from typing import Annotated, Any, Optional

import typer

from cli.commands.flag_utils import validate_output_mode
from cli.commands.templates.render.presenter import present_render_result
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.kv_parser import parse_kv_pairs
from alloy_runtime_types.dtos.templates import RenderTemplateRequest


def templates_render_command(
    template: str = typer.Option(
        ...,
        "-T",
        "--template",
        help="Template name or UUID",
    ),
    variables: Annotated[
        Optional[list[str]],
        typer.Option(
            "-v",
            "--var",
            help="Variable (key=value, key:=json, or key={...}/[...] for nested JSON). Repeatable.",
        ),
    ] = None,
    output: str = typer.Option(
        "console",
        "-o",
        "--output",
        help="Output: console, clipboard, file, editor",
    ),
    output_file: Optional[str] = typer.Option(
        None,
        "-O",
        "--output-file",
        help="Output file path (for --output file)",
    ),
    print_escaped: bool = typer.Option(
        False,
        "--print-escaped",
        help="Print remaining Jinja syntax (from raw blocks)",
    ),
) -> None:
    """Render a template with variables.

    Examples:
        alloy templates render -T my-template -v name=World -v greeting=Hello
        alloy templates render -T email.welcome -v user=John -o clipboard
        alloy templates render -T my-template -v count:=5 -v active:=true
        alloy templates render -T my-template -o file -O output.txt
    """
    validate_output_mode(
        output, output_file, ("console", "clipboard", "file", "editor")
    )

    variables_dict = parse_kv_pairs(variables, parse_object_array_strings=True)

    _execute_render_from_flags(
        template_identifier=template,
        variables_dict=variables_dict,
        output_mode=output,
        output_file=output_file,
        print_escaped=print_escaped,
    )


def _execute_render_from_flags(
    template_identifier: str,
    variables_dict: dict[str, Any] | None,
    output_mode: str,
    output_file: str | None = None,
    print_escaped: bool = False,
) -> None:
    """Execute template rendering from command flags."""
    _execute_render(
        template_identifier=template_identifier,
        variables=variables_dict,
        output_mode=output_mode,
        output_file=output_file,
        print_escaped=print_escaped,
    )


@async_command
async def _execute_render(
    template_identifier: str,
    variables: dict[str, Any] | None,
    output_mode: str,
    output_file: str | None = None,
    print_escaped: bool = False,
) -> None:
    """Execute the template render API call."""
    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."
            )

        request = RenderTemplateRequest(variables=variables or {})
        response = await client.render_template(template_data.template.id, request)

    present_render_result(
        response,
        template_data.template.name,
        output_mode,
        output_file=output_file,
        print_escaped=print_escaped,
    )
