"""Diagnostics support for the KNX integration."""

from typing import Any

import voluptuous as vol

from homeassistant import config as conf_util
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from . import CONFIG_SCHEMA
from .const import (
    CONF_KNX_KNXKEY_PASSWORD,
    CONF_KNX_ROUTING_BACKBONE_KEY,
    CONF_KNX_SECURE_DEVICE_AUTHENTICATION,
    CONF_KNX_SECURE_USER_PASSWORD,
    CONF_KNX_TELEGRAM_DB_POSTGRES_DSN,
    DOMAIN,
    KNX_MODULE_KEY,
)

TO_REDACT = {
    CONF_KNX_ROUTING_BACKBONE_KEY,
    CONF_KNX_KNXKEY_PASSWORD,
    CONF_KNX_SECURE_USER_PASSWORD,
    CONF_KNX_SECURE_DEVICE_AUTHENTICATION,
    CONF_KNX_TELEGRAM_DB_POSTGRES_DSN,
}


async def async_get_config_entry_diagnostics(
    hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
    """Return diagnostics for a config entry."""
    diag: dict[str, Any] = {}
    knx_module = hass.data[KNX_MODULE_KEY]
    diag["xknx"] = {
        "version": knx_module.xknx.version,
        "current_address": str(knx_module.xknx.current_address),
    }

    diag["config_entry_data"] = async_redact_data(dict(config_entry.data), TO_REDACT)
    diag["config_entry_options"] = async_redact_data(
        dict(config_entry.options), TO_REDACT
    )

    if proj_info := knx_module.project.info:
        diag["project_info"] = async_redact_data(proj_info, "name")
    else:
        diag["project_info"] = None

    raw_config = await conf_util.async_hass_config_yaml(hass)
    diag["configuration_yaml"] = raw_config.get(DOMAIN)
    try:
        CONFIG_SCHEMA(raw_config)
    except vol.Invalid as ex:
        diag["yaml_configuration_error"] = str(ex)
    else:
        diag["yaml_configuration_error"] = None

    diag["config_store"] = knx_module.config_store.data

    return diag
