"""Support for Radarr calendar items."""

from datetime import datetime
from typing import override

from homeassistant.components.calendar import (
    CalendarEntity,
    CalendarEntityDescription,
    CalendarEvent,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from .coordinator import CalendarUpdateCoordinator, RadarrConfigEntry, RadarrEvent
from .entity import RadarrEntity

CALENDAR_TYPE = CalendarEntityDescription(
    key="calendar",
    name=None,
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: RadarrConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up the Radarr calendar entity."""
    coordinator = entry.runtime_data.calendar
    async_add_entities([RadarrCalendarEntity(coordinator, CALENDAR_TYPE)])


class RadarrCalendarEntity(RadarrEntity, CalendarEntity):
    """A Radarr calendar entity."""

    coordinator: CalendarUpdateCoordinator

    @property
    @override
    def event(self) -> CalendarEvent | None:
        """Return the next upcoming event."""
        if not self.coordinator.event:
            return None
        return CalendarEvent(
            summary=self.coordinator.event.summary,
            start=self.coordinator.event.start,
            end=self.coordinator.event.end,
            description=self.coordinator.event.description,
        )

    @override
    # pylint: disable-next=home-assistant-return-type
    async def async_get_events(  # type: ignore[override]
        self, hass: HomeAssistant, start_date: datetime, end_date: datetime
    ) -> list[RadarrEvent]:
        """Get all events in a specific time frame."""
        return await self.coordinator.async_get_events(start_date, end_date)

    @callback
    @override
    def _async_write_ha_state(self) -> None:
        """Write the state to the state machine."""
        if self.coordinator.event:
            self._attr_extra_state_attributes = {
                "release_type": self.coordinator.event.release_type
            }
        else:
            self._attr_extra_state_attributes = {}
        super()._async_write_ha_state()
