"""Presenters for pipeline schedules command output."""

from datetime import datetime

from alloy_runtime_types.dtos.schedule import (
    DeleteScheduleResponse,
    GetScheduleResponse,
    ListSchedulesResponse,
)

from cli.infrastructure.output import OutputFormat, OutputService
from cli.infrastructure.renderers.list_renderer import ColumnConfig


def present_schedules_list(response: ListSchedulesResponse) -> None:
    """Present list of schedules with Rich table formatting."""
    output = OutputService.get()

    if getattr(output, "format", OutputFormat.COMPACT) == OutputFormat.JSON:
        output.raw(response)
        return

    columns = [
        ColumnConfig(
            source_field="id",
            header_label="ID",
            compact_line=1,
            compact_style="cyan",
        ),
        ColumnConfig(
            source_field="is_enabled",
            header_label="Enabled",
            formatter=lambda x: "Yes" if x else "No",
            compact_line=1,
            compact_style="green",
        ),
        ColumnConfig(
            source_field="schedule_type",
            header_label="Type",
            compact_line=1,
            compact_style="yellow",
        ),
        ColumnConfig(
            source_field="name",
            header_label="Name",
            compact_line=2,
            compact_style="white bold",
        ),
        ColumnConfig(
            source_field="next_run_at",
            header_label="Next Run",
            formatter=lambda x: x.strftime("%Y-%m-%d %H:%M") if x else "Never",
            compact_line=2,
            compact_style="blue",
        ),
    ]

    output.table(
        items=response.schedules,  # type: ignore[arg-type]
        title=f"Schedules ({response.total})",
        columns=columns,
        raw_payload=response,
        total_count=response.total,
    )


def present_schedule_detail(response: GetScheduleResponse) -> None:
    """Present schedule details with Rich formatting."""
    output = OutputService.get()

    from cli.infrastructure.formatting.fields import format_optional
    from cli.infrastructure.renderers.entity_renderer import FieldConfig

    def _format_datetime_with_tz(dt: datetime | None) -> str:
        """Format datetime with timezone."""
        return format_optional(dt, lambda x: x.strftime("%Y-%m-%d %H:%M:%S %Z"))

    fields = [
        FieldConfig("id", "Schedule ID", str),
        FieldConfig("pipeline_id", "Pipeline ID", str),
        FieldConfig("name", "Name"),
        FieldConfig("description", "Description", format_optional),
        FieldConfig("schedule_type", "Type"),
        FieldConfig("timezone", "Timezone"),
        FieldConfig("is_enabled", "Enabled", lambda v: "Yes" if v else "No"),
        FieldConfig("cron_expression", "Cron Expression", format_optional),
        FieldConfig("rrule_freq", "RRULE Freq", format_optional),
        FieldConfig(
            "rrule_interval", "RRULE Interval", lambda v: str(v) if v and v > 1 else "-"
        ),
        FieldConfig("next_run_at", "Next Run", _format_datetime_with_tz),
        FieldConfig("last_run_at", "Last Run", _format_datetime_with_tz),
        FieldConfig("consecutive_failures", "Consecutive Failures", str),
        FieldConfig(
            "allow_concurrent", "Allow Concurrent", lambda v: "Yes" if v else "No"
        ),
        FieldConfig("max_consecutive_failures", "Max Failures", str),
    ]

    output.entity(response, f"Schedule: {response.name}", fields, raw_payload=response)


def present_delete_result(response: DeleteScheduleResponse) -> None:
    """Present schedule deletion result."""
    output = OutputService.get()
    output.result(
        action="delete",
        resource="schedule",
        identifier=str(response.id),
        name=None,
    )
