"""Update entities for Netgear devices."""

import logging
from typing import Any, override

from homeassistant.components.update import (
    UpdateDeviceClass,
    UpdateEntity,
    UpdateEntityFeature,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from .coordinator import NetgearConfigEntry, NetgearFirmwareCoordinator
from .entity import NetgearRouterCoordinatorEntity

LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: NetgearConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up update entities for Netgear component."""
    coordinator = entry.runtime_data.coordinator_firmware
    entities = [NetgearUpdateEntity(coordinator)]

    async_add_entities(entities)


class NetgearUpdateEntity(
    NetgearRouterCoordinatorEntity[NetgearFirmwareCoordinator], UpdateEntity
):
    """Update entity for a Netgear device."""

    _attr_device_class = UpdateDeviceClass.FIRMWARE
    _attr_supported_features = UpdateEntityFeature.INSTALL

    def __init__(
        self,
        coordinator: NetgearFirmwareCoordinator,
    ) -> None:
        """Initialize a Netgear device."""
        super().__init__(coordinator)
        self._attr_unique_id = f"{coordinator.router.serial_number}-update"  # pylint: disable=home-assistant-entity-unique-id-redundant-platform

    @property
    @override
    def installed_version(self) -> str | None:
        """Version currently in use."""
        if self.coordinator.data is not None:
            return self.coordinator.data.get("CurrentVersion")
        return None

    @property
    @override
    def latest_version(self) -> str | None:
        """Latest version available for install."""
        if self.coordinator.data is not None:
            new_version = self.coordinator.data.get("NewVersion")
            if new_version is not None and not new_version.startswith(
                self.installed_version
            ):
                return new_version
        return self.installed_version

    @property
    @override
    def release_summary(self) -> str | None:
        """Release summary."""
        if self.coordinator.data is not None:
            return self.coordinator.data.get("ReleaseNote")
        return None

    @override
    async def async_install(
        self, version: str | None, backup: bool, **kwargs: Any
    ) -> None:
        """Install the latest firmware version."""
        await self._router.async_update_new_firmware()

    @callback
    @override
    def async_update_device(self) -> None:
        """Update the Netgear device."""
