from uuid import UUID
from typing import Annotated

import typer

from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.schedules.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.schedule import SetScheduleEnvVarsRequest


def pipelines_schedules_env_vars_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    schedule_id: str = typer.Argument(
        ...,
        help="Schedule 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 schedule.

    Schedule-level env vars override pipeline-level env vars when the
    schedule triggers execution.

    Examples:
        alloy pipelines schedules env-vars 123e4567... 456e7890... --env API_KEY=secret
        alloy pipelines schedules env-vars 123e4567... 456e7890... -e KEY1=val1 -e KEY2=val2
        alloy pipelines schedules env-vars 123e4567... 456e7890...
    """
    p_uuid = validate_uuid(pipeline_id, "pipeline")
    s_uuid = validate_uuid(schedule_id, "schedule")
    env_vars = parse_kv_pairs(env)

    _execute_set(pipeline_id=p_uuid, schedule_id=s_uuid, env_vars=env_vars)


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

    present_set_env_vars_result(response)
