"""Pipeline schedule once command implementation."""

import json
from typing import Annotated, Any
from uuid import UUID

import typer

from alloy_runtime_types.dtos.schedule import ScheduleOnceRequest
from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.schedules.once_presenter import present_once_result
from cli.infrastructure.command import async_command, authenticated_client


def pipelines_schedules_once_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    scheduled_for: str = typer.Option(
        ...,
        "--scheduled-for",
        "-s",
        help="When to execute (ISO 8601 datetime, e.g. 2026-03-01T15:00:00)",
    ),
    timezone: str = typer.Option(
        "UTC",
        "--timezone",
        "-tz",
        help="IANA timezone for interpreting scheduled_for",
    ),
    input_params: Annotated[
        str | None,
        typer.Option(
            "--input-params",
            "-i",
            help="Input parameters as JSON string",
        ),
    ] = None,
    timeout: int = typer.Option(
        300,
        "--timeout",
        "-t",
        help="Execution timeout in seconds (1-3600)",
        min=1,
        max=3600,
    ),
) -> None:
    """Schedule a one-time pipeline execution.

    Examples:
        alloy pipelines schedules once 123e4567... --scheduled-for 2026-03-01T15:00:00
        alloy pipelines schedules once 123e4567... -s 2026-03-01T15:00:00 --timezone America/New_York
        alloy pipelines schedules once 123e4567... -s 2026-03-01T15:00:00 -i '{"key": "value"}'
    """
    from datetime import datetime as dt

    p_uuid = validate_uuid(pipeline_id, "pipeline")

    try:
        scheduled_dt = dt.fromisoformat(scheduled_for)
    except ValueError:
        raise typer.BadParameter(
            f"Invalid datetime format: '{scheduled_for}'. Use ISO 8601 (e.g. 2026-03-01T15:00:00)"
        )

    params: dict[str, Any] = {}
    if input_params:
        try:
            params = json.loads(input_params)
        except json.JSONDecodeError as e:
            raise typer.BadParameter(f"Invalid JSON for --input-params: {e}")

    request = ScheduleOnceRequest(
        scheduled_for=scheduled_dt,
        timezone=timezone,
        input_parameters=params,
        timeout_seconds=timeout,
    )

    _execute_once(pipeline_id=p_uuid, request=request)


@async_command
async def _execute_once(pipeline_id: UUID, request: ScheduleOnceRequest) -> None:
    """Execute schedule-once operation."""
    async with authenticated_client() as (_config, client):
        response = await client.schedule_pipeline_once(pipeline_id, request)

    present_once_result(response)
