"""Pipeline schedule create command implementation."""

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

import typer

from alloy_runtime_types.dtos.schedule import (
    CreateScheduleRequest,
    CronSchedule,
)
from cli.commands.flag_utils import validate_uuid
from cli.commands.pipelines.schedules.create_presenter import present_create_result
from cli.infrastructure.command import async_command, authenticated_client


def pipelines_schedules_create_command(
    pipeline_id: str = typer.Argument(
        ...,
        help="Pipeline UUID",
    ),
    name: str = typer.Option(
        ...,
        "-n",
        "--name",
        help="Schedule name",
    ),
    cron: str = typer.Option(
        ...,
        "--cron",
        help="Cron expression (5 fields: minute hour day month weekday)",
    ),
    description: Annotated[
        str | None,
        typer.Option(
            "-d",
            "--description",
            help="Schedule description",
        ),
    ] = None,
    timezone: str = typer.Option(
        "UTC",
        "--timezone",
        "-tz",
        help="IANA timezone (e.g. America/Chicago, Europe/London)",
    ),
    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,
    ),
    disabled: bool = typer.Option(
        False,
        "--disabled",
        help="Create schedule in disabled state",
    ),
    allow_concurrent: bool = typer.Option(
        False,
        "--allow-concurrent",
        help="Allow concurrent executions",
    ),
    max_failures: int = typer.Option(
        5,
        "--max-failures",
        help="Auto-disable after this many consecutive failures (0 = never)",
        min=0,
    ),
) -> None:
    """Create a recurring schedule for a pipeline.

    Examples:
        alloy pipelines schedules create 123e4567... -n 'Daily Report' --cron '0 9 * * *'
        alloy pipelines schedules create 123e4567... -n 'Weekly' --cron '0 9 * * 1' --timezone America/Chicago
        alloy pipelines schedules create 123e4567... -n 'Hourly' --cron '0 * * * *' -i '{"key": "value"}'
    """
    p_uuid = validate_uuid(pipeline_id, "pipeline")

    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}")

    schedule_expr = CronSchedule(expression=cron, timezone=timezone)

    request = CreateScheduleRequest(
        name=name,
        description=description,
        schedule=schedule_expr,
        input_parameters=params,
        timeout_seconds=timeout,
        is_enabled=not disabled,
        allow_concurrent=allow_concurrent,
        max_consecutive_failures=max_failures,
    )

    _execute_create(pipeline_id=p_uuid, request=request)


@async_command
async def _execute_create(pipeline_id: UUID, request: CreateScheduleRequest) -> None:
    """Execute create schedule operation."""
    async with authenticated_client() as (_config, client):
        response = await client.create_pipeline_schedule(pipeline_id, request)

    present_create_result(response)
