"""Support for Lutron Powr Savr occupancy sensors."""

from collections.abc import Mapping
from typing import Any, override

from pylutron import OccupancyGroup

from homeassistant.components.binary_sensor import (
    BinarySensorDeviceClass,
    BinarySensorEntity,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from . import LutronConfigEntry
from .entity import LutronDevice


async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: LutronConfigEntry,
    async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
    """Set up the Lutron binary_sensor platform.

    Adds occupancy groups from the Main Repeater associated with the
    config_entry as binary_sensor entities.
    """
    entry_data = config_entry.runtime_data
    async_add_entities(
        [
            LutronOccupancySensor(
                hass, area_name, device, entry_data.client, config_entry.entry_id
            )
            for area_name, device in entry_data.binary_sensors
        ],
        True,
    )


class LutronOccupancySensor(LutronDevice, BinarySensorEntity):
    """Representation of a Lutron Occupancy Group.

    The Lutron integration API reports "occupancy groups" rather than
    individual sensors. If two sensors are in the same room, they're
    reported as a single occupancy group.
    """

    _lutron_device: OccupancyGroup
    _attr_device_class = BinarySensorDeviceClass.OCCUPANCY

    @property
    @override
    def extra_state_attributes(self) -> Mapping[str, Any] | None:
        """Return the state attributes."""
        return {"lutron_integration_id": self._lutron_device.id}

    @override
    def _update_attrs(self) -> None:
        """Update the state attributes."""
        self._attr_is_on = self._lutron_device.state is OccupancyGroup.State.OCCUPIED
