"""Support for the Zeversolar platform."""

from collections.abc import Callable
from dataclasses import dataclass
from typing import override

import zeversolar

from homeassistant.components.sensor import (
    SensorDeviceClass,
    SensorEntity,
    SensorEntityDescription,
    SensorStateClass,
)
from homeassistant.const import UnitOfEnergy, UnitOfPower
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from .coordinator import ZeversolarConfigEntry, ZeversolarCoordinator
from .entity import ZeversolarEntity


@dataclass(frozen=True, kw_only=True)
class ZeversolarEntityDescription(SensorEntityDescription):
    """Describes Zeversolar sensor entity."""

    value_fn: Callable[[zeversolar.ZeverSolarData], zeversolar.kWh | zeversolar.Watt]


SENSOR_TYPES = (
    ZeversolarEntityDescription(
        key="pac",
        native_unit_of_measurement=UnitOfPower.WATT,
        state_class=SensorStateClass.MEASUREMENT,
        device_class=SensorDeviceClass.POWER,
        value_fn=lambda data: data.pac,
    ),
    ZeversolarEntityDescription(
        key="energy_today",
        translation_key="energy_today",
        native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
        state_class=SensorStateClass.TOTAL_INCREASING,
        device_class=SensorDeviceClass.ENERGY,
        value_fn=lambda data: data.energy_today,
    ),
)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ZeversolarConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up the Zeversolar sensor."""
    coordinator = entry.runtime_data
    async_add_entities(
        ZeversolarSensor(
            description=description,
            coordinator=coordinator,
        )
        for description in SENSOR_TYPES
    )


class ZeversolarSensor(ZeversolarEntity, SensorEntity):
    """Implementation of the Zeversolar sensor."""

    entity_description: ZeversolarEntityDescription

    def __init__(
        self,
        *,
        description: ZeversolarEntityDescription,
        coordinator: ZeversolarCoordinator,
    ) -> None:
        """Initialize the sensor."""
        self.entity_description = description
        super().__init__(coordinator=coordinator)
        self._attr_unique_id = f"{coordinator.data.serial_number}_{description.key}"

    @property
    @override
    def native_value(self) -> int | float:
        """Return sensor state."""
        return self.entity_description.value_fn(self.coordinator.data)
