"""The Nightscout integration."""

from aiohttp import ClientError
from py_nightscout import Api as NightscoutAPI

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_URL, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import SLOW_UPDATE_WARNING

from .const import DOMAIN

PLATFORMS = [Platform.SENSOR]
_API_TIMEOUT = SLOW_UPDATE_WARNING - 1

type NightscoutConfigEntry = ConfigEntry[NightscoutAPI]


async def async_setup_entry(hass: HomeAssistant, entry: NightscoutConfigEntry) -> bool:
    """Set up Nightscout from a config entry."""
    server_url = entry.data[CONF_URL]
    api_key = entry.data.get(CONF_API_KEY)
    session = async_get_clientsession(hass)
    api = NightscoutAPI(server_url, session=session, api_secret=api_key)
    try:
        status = await api.get_server_status()
    except (ClientError, TimeoutError, OSError) as error:
        raise ConfigEntryNotReady from error

    entry.runtime_data = api

    device_registry = dr.async_get(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={(DOMAIN, server_url)},
        manufacturer="Nightscout Foundation",
        name=status.name,
        sw_version=status.version,
        entry_type=dr.DeviceEntryType.SERVICE,
    )

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True


async def async_unload_entry(hass: HomeAssistant, entry: NightscoutConfigEntry) -> bool:
    """Unload a config entry."""
    return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
