from uuid import UUID
from typing import Annotated

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.env_vars.presenter import present_set_env_vars_result
from cli.infrastructure.command import async_command, authenticated_client
from cli.infrastructure.kv_parser import parse_kv_pairs

from alloy_runtime_types.dtos.pipeline import SetPipelineEnvVarsRequest


def pipelines_env_vars_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    env: Annotated[
        list[str] | None,
        typer.Option(
            "--env",
            "-e",
            help="Environment variable in KEY=VALUE format (repeatable). Pass no values to clear all.",
        ),
    ] = None,
) -> None:
    """Set environment variables on a pipeline.

    Environment variables are encrypted at rest and injected into pipeline
    executions. They can be overridden at execution time.

    Examples:
        alloy pipelines env-vars 123e4567... --env API_KEY=secret
        alloy pipelines env-vars 123e4567... -e KEY1=val1 -e KEY2=val2
        alloy pipelines env-vars 123e4567... --env PORT:=8080
        alloy pipelines env-vars 123e4567...
    """
    pipeline_uuid = validate_uuid(pipeline_id, "pipeline")
    env_vars = parse_kv_pairs(env)

    _execute_set(pipeline_id=pipeline_uuid, env_vars=env_vars)


@async_command
async def _execute_set(pipeline_id: UUID, env_vars: dict[str, str]) -> None:
    async with authenticated_client() as (_config, client):
        request = SetPipelineEnvVarsRequest(env_vars=env_vars)
        response = await client.set_pipeline_env_vars(pipeline_id, request)

    present_set_env_vars_result(response)
