"""Switch platform for Greenhousino Irrigation."""

import logging
from typing import Any

from homeassistant.components import mqtt
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import (
    ATTR_PUMP_ACTIVE,
    DOMAIN,
    MANUFACTURER,
    MODEL,
)

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up Greenhousino switch from config entry."""
    hass_data = entry.runtime_data

    async_add_entities(
        [
            GreenhousinoPumpSwitch(
                entry,
                hass_data.command_topic,
                hass_data.state_topic,
            )
        ]
    )


class GreenhousinoPumpSwitch(SwitchEntity):
    """Representation of a Greenhousino pump switch."""

    _attr_has_entity_name = True
    _attr_name = "Pump"
    _attr_should_poll = False
    _attr_unique_id = None  # will be set from entry_id
    _entry_id = None

    def __init__(
        self,
        entry: ConfigEntry,
        command_topic: str,
        state_topic: str,
    ) -> None:
        """Initialize the switch."""
        self._command_topic = command_topic
        self._state_topic = state_topic
        self._entry_id = entry.entry_id
        self._attr_unique_id = f"{entry.entry_id}-pump"
        self._attr_available = False
        self._state = False

    @property
    def device_info(self):
        """Return device info."""
        return {
            "identifiers": {(DOMAIN, self._entry_id)},
            "manufacturer": MANUFACTURER,
            "model": MODEL,
        }

    async def async_added_to_hass(self) -> None:
        """Register callbacks."""
        entry = self.config_entry

        self.async_on_remove(
            mqtt.async_subscribe(
                self.hass,
                self._state_topic,
                self._state_received,
                qos=1,
            )
        )

        # Publish availability via MQTT discovery-style
        # The device publishes to greenhousino/pump/status with "offline" on disconnect
        status_topic = self._state_topic.replace("pumpstate", "pump/status")
        self.async_on_remove(
            mqtt.async_subscribe(
                self.hass,
                status_topic,
                self._availability_received,
                qos=1,
            )
        )

    def _state_received(self, msg: mqtt.MqttReceivePayload) -> None:
        """Handle new MQTT state message."""
        payload = msg.decode().strip()
        self._state = payload == "on"
        self._attr_available = True
        self.async_write_ha_state()
        _LOGGER.debug("State received: %s -> pump_active=%s", payload, self._state)

    def _availability_received(self, msg: mqtt.MqttReceivePayload) -> None:
        """Handle availability message."""
        payload = msg.decode().strip()
        self._attr_available = payload != "offline"
        self.async_write_ha_state()
        _LOGGER.debug("Availability: %s", payload)

    @property
    def is_on(self) -> bool:
        """Return True if the pump is on."""
        return self._state

    @property
    def extra_state_attributes(self) -> dict[str, Any]:
        """Return device state attributes."""
        return {
            ATTR_PUMP_ACTIVE: self._state,
            "command_topic": self._command_topic,
            "state_topic": self._state_topic,
            "manufacturer": MANUFACTURER,
            "model": MODEL,
        }

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Turn the pump on."""
        await mqtt.async_publish(
            self.hass,
            self._command_topic,
            "on",
            qos=1,
            retain=False,
        )
        self._state = True
        self.async_write_ha_state()

    async def async_turn_off(self) -> None:
        """Turn the pump off."""
        await mqtt.async_publish(
            self.hass,
            self._command_topic,
            "off",
            qos=1,
            retain=False,
        )
        self._state = False
        self.async_write_ha_state()
