Source code for aiopnsense.system

"""System and configuration methods for OPNsenseClient."""

from collections.abc import Mapping, MutableMapping
from datetime import datetime, timedelta, timezone, tzinfo
import re
from typing import Any, NamedTuple
import warnings

import aiohttp
from dateutil.parser import ParserError, UnknownTimezoneWarning, parse

from ._error_policy import _log_errors, _raise_if_throwing
from ._styled_endpoint import _StyledEndpoint
from ._typing import AiopnsenseClientProtocol
from .access import Access, AccessDict
from .client_toggle import ToggleSpec, ToggleStep, ToggleTarget
from .const import (
    AMBIGUOUS_TZINFOS,
    INTERFACE_ASSIGNMENT_CAPABILITY,
    NEW_CARP_STATUS_ENDPOINT_CAPABILITY,
)
from .exceptions import OPNsenseError, OPNsenseInvalidArgument, OPNsenseMissingDeviceUniqueID
from .helpers import (
    _LOGGER,
    api_value_matches,
    coerce_bool,
    normalize_lookup_token,
    timestamp_to_datetime,
    try_to_int,
)

SYSTEM_TIME_ENDPOINT = _StyledEndpoint(
    snake_case="/api/diagnostics/system/system_time",
    camel_case="/api/diagnostics/system/systemTime",
)
INTERFACE_OVERVIEW_EXPORT_ENDPOINT = "/api/interfaces/overview/export"
SYSTEM_INFORMATION_ENDPOINT = _StyledEndpoint(
    snake_case="/api/diagnostics/system/system_information",
    camel_case="/api/diagnostics/system/systemInformation",
)
CARP_VIP_STATUS_ENDPOINT = "/api/diagnostics/interface/get_vip_status"
VIP_SETTINGS_ENDPOINT = "/api/interfaces/vip_settings/get"
CORE_SYSTEM_REBOOT_ENDPOINT = "/api/core/system/reboot"
CORE_SYSTEM_HALT_ENDPOINT = "/api/core/system/halt"
CARP_STATUS_ENDPOINT = _StyledEndpoint(
    snake_case="/api/diagnostics/interface/_carp_status",
    camel_case="/api/diagnostics/interface/CarpStatus",
)
CARP_STATUS_26_1_11_SNAKE_ENDPOINT = "/api/diagnostics/interface/carp_status"
CARP_MAINTENANCE_ENDPOINT_SUFFIX = "/maintenance"
WOL_SET_ENDPOINT = "/api/wol/wol/set"
CORE_SYSTEM_STATUS_ENDPOINT = "/api/core/system/status"
CORE_SYSTEM_DISMISS_ENDPOINT = _StyledEndpoint(
    snake_case="/api/core/system/dismiss_status",
    camel_case="/api/core/system/dismissStatus",
)
INTERFACE_OVERVIEW_RELOAD_ENDPOINT_PREFIX = _StyledEndpoint(
    snake_case="/api/interfaces/overview/reload_interface/",
    camel_case="/api/interfaces/overview/reloadInterface/",
)
CERT_SEARCH_ENDPOINT = "/api/trust/cert/search"
INTERFACE_ASSIGNMENT_GET_ITEM_ENDPOINT_PREFIX = "/api/interfaces/assignment/get_item/"
INTERFACE_ASSIGNMENT_SET_ITEM_ENDPOINT_PREFIX = "/api/interfaces/assignment/set_item/"
INTERFACE_ASSIGNMENT_PENDING_ENDPOINT = "/api/interfaces/assignment/pending"
INTERFACE_ASSIGNMENT_RECONFIGURE_ENDPOINT = "/api/interfaces/assignment/reconfigure"

_INTERFACE_IDENTIFIER_PATTERN = re.compile(r"(?:wan|lan|opt[1-9][0-9]*)\Z")


class _CarpSettingsIndexes(NamedTuple):
    """Lookup indexes used to match CARP status rows to VIP settings."""

    by_full: dict[tuple[str, str, str], dict[str, Any]]
    by_if_subnet: dict[tuple[str, str], list[dict[str, Any]]]
    by_if_vhid: dict[tuple[str, str], list[dict[str, Any]]]
    by_subnet: dict[str, list[dict[str, Any]]]
    by_vhid: dict[str, list[dict[str, Any]]]


class SystemMixin(AiopnsenseClientProtocol):
    """System methods for OPNsenseClient."""

    @staticmethod
    def _validate_interface_identifier(if_name: str) -> None:
        """Reject interface identifiers that cannot safely address an assignment item.

        Args:
            if_name (str): Logical OPNsense interface identifier.

        Raises:
            OPNsenseInvalidArgument: The value is not ``wan``, ``lan``, or ``optN``.
        """
        if not isinstance(if_name, str) or _INTERFACE_IDENTIFIER_PATTERN.fullmatch(if_name) is None:
            raise OPNsenseInvalidArgument(
                "`if_name` must be a logical interface identifier such as 'wan', 'lan', or 'opt1'."
            )

    async def _read_interface_config(self, if_name: str) -> dict[str, Any]:
        """Fetch raw settings only when the API confirms the requested item identity.

        Args:
            if_name (str): Logical OPNsense interface identifier.

        Returns:
            dict[str, Any]: Raw interface settings, or an empty mapping when unreadable.
        """
        response = await self._safe_dict_get(
            f"{INTERFACE_ASSIGNMENT_GET_ITEM_ENDPOINT_PREFIX}{if_name}"
        )
        interface = response.get("interface")
        if not isinstance(interface, MutableMapping) or interface.get("identifier") != if_name:
            return {}
        return dict(interface)

    @_log_errors
    async def toggle_interface(self, if_name: str, toggle_on_off: str | None = None) -> bool | None:
        """Toggle an interface's enabled state and apply the resulting configuration.

        Requires firmware >= 26.7.6 and sends only the enable flag. Refuses
        pending or unreadable interface work; coordinate concurrent changes.
        Failure or cancellation can leave pending work: resolve it in the
        OPNsense UI before retrying. Applying changes can reset queued
        interfaces' advanced/file-based DHCP settings or disconnect this client.

        Args:
            if_name (str): Logical interface identifier such as ``wan``, ``lan``, or ``opt8``.
            toggle_on_off (str | None, optional): Target state. Use ``on`` to
                enable, ``off`` to disable, or ``None`` or ``toggle`` to invert
                the current state.

        Returns:
            bool | None: True when already matching, or when the Router
                acknowledged the save (``saved``) and confirmed the apply;
                False when refused, the save was not acknowledged (no apply is
                sent) or the apply was not confirmed. A suppressed exception
                returns None. With ``throw_errors`` enabled, invalid arguments
                raise ``OPNsenseInvalidArgument`` and transport failures raise
                ``OPNsenseError`` subclasses.
        """
        self._validate_interface_identifier(if_name)
        target = self._parse_toggle_target(toggle_on_off)
        if not await self._firmware_capability_enabled(INTERFACE_ASSIGNMENT_CAPABILITY):
            return False

        pending_response = await self._safe_dict_get(INTERFACE_ASSIGNMENT_PENDING_ENDPOINT)
        pending_status = pending_response.get("status")
        if not isinstance(pending_status, str) or pending_status.strip().lower() != "ok":
            _LOGGER.debug(
                "Refusing to change interface %s because pending interface state is not clear. "
                "Review and resolve pending configuration in the OPNsense UI before retrying",
                if_name,
            )
            return False

        interface = await self._read_interface_config(if_name)
        current_enabled = interface.get("enable")
        if not interface or not (
            api_value_matches(current_enabled, "0") or api_value_matches(current_enabled, "1")
        ):
            _LOGGER.debug("Unable to read enabled state for interface %s", if_name)
            return False
        if target is ToggleTarget.FLIP:
            target = (
                ToggleTarget.OFF if api_value_matches(current_enabled, "1") else ToggleTarget.ON
            )
        desired_value = "1" if target is ToggleTarget.ON else "0"
        if api_value_matches(current_enabled, desired_value):
            return True

        saved = await self._run_toggle(
            ToggleSpec(
                label="toggle_interface",
                target=target,
                save=(
                    ToggleStep.save(
                        f"{INTERFACE_ASSIGNMENT_SET_ITEM_ENDPOINT_PREFIX}{if_name}",
                        frozenset({"saved"}),
                        payload={"interface": {"enable": desired_value}},
                    ),
                ),
                apply=(),
            )
        )
        if not saved:
            return False

        applied = await self._run_toggle(
            ToggleSpec(
                label="toggle_interface",
                target=target,
                save=(),
                apply=(ToggleStep.apply(INTERFACE_ASSIGNMENT_RECONFIGURE_ENDPOINT, payload={}),),
            )
        )
        if not applied:
            _LOGGER.warning(
                "Interface %s was saved, but reconfiguration did not report success; the "
                "apply outcome may be uncertain. Review pending configuration in the "
                "OPNsense UI before retrying, and do not blindly repeat the global reconfigure",
                if_name,
            )
        return applied

    def _handle_missing_device_unique_id(self) -> None:
        """Raise when device unique ID resolution failed in throwing mode.

        Returns:
            None: Nothing when ``throw_errors`` is disabled. When it is enabled,
                ``OPNsenseMissingDeviceUniqueID`` is raised through the error
                policy because no device unique ID could be resolved.
        """
        _raise_if_throwing(self, OPNsenseMissingDeviceUniqueID())

    def _parse_carp_vip_rows(self, rows: list[Any]) -> list[dict[str, Any]]:
        """Normalize CARP VIP rows from OPNsense responses.

        Args:
            rows (list[Any]): Raw VIP rows returned by OPNsense endpoints.

        Returns:
            list[dict[str, Any]]: Filtered CARP VIP rows with normalized status values.
        """
        parsed_rows: list[dict[str, Any]] = []
        for row in rows:
            if not isinstance(row, MutableMapping):
                continue
            mode = normalize_lookup_token(row.get("mode", ""))
            if mode and mode != "carp":
                continue
            row_copy = dict(row)
            raw_status = row_copy.get("status")
            status_str = str(raw_status).strip() if raw_status is not None else ""
            if not status_str:
                row_copy["status"] = "DISABLED"
            else:
                row_copy["status"] = status_str.upper()
            parsed_rows.append(row_copy)
        return parsed_rows

    @staticmethod
    def _classify_carp_state(
        has_carp_block: bool,
        has_rows: bool,
        enabled: bool,
        maintenance_mode: bool,
        vip_count: int,
        demotion: int,
        status_message: str,
        other_count: int,
    ) -> str:
        """Classify aggregate CARP state from normalized summary values.

        Args:
            has_carp_block (bool): Whether the response contains a CARP metadata block.
            has_rows (bool): Whether the response contains VIP rows.
            enabled (bool): Whether CARP is enabled.
            maintenance_mode (bool): Whether CARP maintenance mode is active.
            vip_count (int): Number of CARP VIP entries.
            demotion (int): Current CARP demotion counter.
            status_message (str): CARP status message from OPNsense.
            other_count (int): Count of VIPs in neither MASTER nor BACKUP state.

        Returns:
            str: Derived CARP state classification.
        """
        if not has_carp_block and not has_rows:
            return "unknown"
        if not enabled:
            return "disabled"
        if maintenance_mode:
            return "maintenance"
        if vip_count == 0:
            return "not_configured"
        if demotion != 0 or bool(status_message.strip()) or other_count > 0:
            return "degraded"
        return "healthy"

    @staticmethod
    def _select_carp_setting_candidate(
        candidates: list[dict[str, Any]],
        interface_key: str,
        vhid_key: str,
        subnet_key: str,
    ) -> dict[str, Any] | None:
        """Select the best fallback VIP setting candidate for a status row.

        Args:
            candidates (list[dict[str, Any]]): Candidate VIP settings with partial key collisions.
            interface_key (str): Normalized interface key from the status row.
            vhid_key (str): Normalized VHID key from the status row.
            subnet_key (str): Normalized subnet key from the status row.

        Returns:
            dict[str, Any] | None: Best-matching candidate, or ``None`` when unavailable.
        """
        best_candidate: dict[str, Any] | None = None
        best_score = -1
        has_ambiguous_tie = False
        for candidate in candidates:
            score = 0
            candidate_interface = normalize_lookup_token(candidate.get("interface", ""))
            candidate_vhid = normalize_lookup_token(candidate.get("vhid", ""))
            candidate_subnet = normalize_lookup_token(candidate.get("subnet", ""))
            if interface_key and candidate_interface == interface_key:
                score += 1
            if vhid_key and candidate_vhid == vhid_key:
                score += 1
            if subnet_key and candidate_subnet == subnet_key:
                score += 1
            if score > best_score:
                best_candidate = candidate
                best_score = score
                has_ambiguous_tie = False
            elif score == best_score:
                best_candidate = None
                has_ambiguous_tie = True
        if has_ambiguous_tie:
            return None
        return best_candidate

    def _merge_carp_vip_rows(
        self,
        vip_status_rows: list[Any],
        vip_settings_rows: list[Any],
    ) -> list[dict[str, Any]]:
        """Merge CARP VIP status rows with VIP settings rows.

        Args:
            vip_status_rows (list[Any]): Raw rows from the VIP status endpoint.
            vip_settings_rows (list[Any]): Raw rows from the VIP settings endpoint.

        Returns:
            list[dict[str, Any]]: Merged CARP VIP rows with normalized subnet values.
        """
        vip_status = self._parse_carp_vip_rows(vip_status_rows)

        vip_settings: list[dict[str, Any]] = []
        for row in vip_settings_rows:
            if not isinstance(row, MutableMapping):
                continue
            mode = normalize_lookup_token(row.get("mode", ""))
            if mode and mode != "carp":
                continue
            vip_settings.append(dict(row))

        settings_indexes = self._build_carp_settings_indexes(vip_settings)

        merged_vips: list[dict[str, Any]] = []
        for status_vip in vip_status:
            settings_match = self._find_carp_settings_match(status_vip, settings_indexes)

            if settings_match is None:
                merged_vip = dict(status_vip)
            else:
                merged_vip = dict(settings_match)
                merged_vip.update(status_vip)

            subnet_value = merged_vip.get("subnet")
            if isinstance(subnet_value, str):
                subnet_value = subnet_value.strip()
                if subnet_value:
                    merged_vip["subnet"] = subnet_value
            if not subnet_value:
                continue
            interface_value = merged_vip.get("interface")
            if isinstance(interface_value, str):
                interface_value = interface_value.strip()
                if interface_value:
                    merged_vip["interface"] = interface_value
            if not interface_value:
                continue
            merged_vips.append(merged_vip)

        return merged_vips

    def _build_carp_settings_indexes(
        self,
        vip_settings: list[dict[str, Any]],
    ) -> _CarpSettingsIndexes:
        """Build CARP setting indexes used by fallback matching.

        Args:
            vip_settings (list[dict[str, Any]]): Normalized CARP VIP settings rows.

        Returns:
            _CarpSettingsIndexes: Lookup dictionaries keyed by full identity and partial keys.
        """
        settings_indexes = _CarpSettingsIndexes(
            by_full={},
            by_if_subnet={},
            by_if_vhid={},
            by_subnet={},
            by_vhid={},
        )
        for setting in vip_settings:
            interface_key = normalize_lookup_token(setting.get("interface"))
            vhid_key = normalize_lookup_token(setting.get("vhid"))
            subnet_key = normalize_lookup_token(setting.get("subnet"))
            settings_indexes.by_full[(interface_key, vhid_key, subnet_key)] = setting
            if interface_key and subnet_key:
                settings_indexes.by_if_subnet.setdefault((interface_key, subnet_key), []).append(
                    setting
                )
            if interface_key and vhid_key:
                settings_indexes.by_if_vhid.setdefault((interface_key, vhid_key), []).append(
                    setting
                )
            if subnet_key:
                settings_indexes.by_subnet.setdefault(subnet_key, []).append(setting)
            if vhid_key:
                settings_indexes.by_vhid.setdefault(vhid_key, []).append(setting)
        return settings_indexes

    def _find_carp_settings_match(
        self,
        status_vip: dict[str, Any],
        settings_indexes: _CarpSettingsIndexes,
    ) -> dict[str, Any] | None:
        """Find the best settings row for one CARP status row.

        Args:
            status_vip (dict[str, Any]): Parsed CARP status row.
            settings_indexes (_CarpSettingsIndexes): Lookup dictionaries generated from CARP settings rows.

        Returns:
            dict[str, Any] | None: Best matching settings row, or ``None`` when no unambiguous fallback exists.
        """
        interface_key = normalize_lookup_token(status_vip.get("interface"))
        vhid_key = normalize_lookup_token(status_vip.get("vhid"))
        subnet_key = normalize_lookup_token(status_vip.get("subnet"))

        settings_match = settings_indexes.by_full.get((interface_key, vhid_key, subnet_key))
        if settings_match is None and interface_key and subnet_key:
            settings_match = self._select_carp_setting_candidate(
                settings_indexes.by_if_subnet.get((interface_key, subnet_key), []),
                interface_key,
                vhid_key,
                subnet_key,
            )
        if settings_match is None and interface_key and vhid_key:
            settings_match = self._select_carp_setting_candidate(
                settings_indexes.by_if_vhid.get((interface_key, vhid_key), []),
                interface_key,
                vhid_key,
                subnet_key,
            )
        if settings_match is None and subnet_key:
            settings_match = self._select_carp_setting_candidate(
                settings_indexes.by_subnet.get(subnet_key, []),
                interface_key,
                vhid_key,
                subnet_key,
            )
        if settings_match is None and vhid_key:
            settings_match = self._select_carp_setting_candidate(
                settings_indexes.by_vhid.get(vhid_key, []),
                interface_key,
                vhid_key,
                subnet_key,
            )
        return settings_match

    def _get_local_timezone(self) -> tzinfo:
        """Return a local timezone fallback with fixed UTC offset.

        Returns:
            tzinfo: Resolved timezone object for OPNsense system data.
        """
        return timezone(datetime.now().astimezone().utcoffset() or timedelta())

    def _parse_opnsense_tz(self, datetime_str: str | None) -> tzinfo | None:
        """Parse a timezone from a system timestamp string.

        Args:
            datetime_str (str | None): Raw timestamp value from the system
                endpoint.

        Returns:
            tzinfo | None: Parsed timezone when available; ``None`` when the
                string is missing, naive, or cannot be parsed.
        """
        if not datetime_str:
            return None

        try:
            with warnings.catch_warnings():
                warnings.simplefilter("error", UnknownTimezoneWarning)
                parsed_time = parse(datetime_str, tzinfos=AMBIGUOUS_TZINFOS)
            if parsed_time.tzinfo is not None:
                return parsed_time.tzinfo
            _LOGGER.debug("No timezone data in OPNsense datetime '%s'", datetime_str)
        except (ValueError, TypeError, ParserError, UnknownTimezoneWarning) as err:
            _LOGGER.debug(
                "Failed to parse OPNsense timezone from datetime '%s': %s: %s",
                datetime_str,
                type(err).__name__,
                err,
            )
        return None

    async def _get_resolved_opnsense_timezone(
        self, datetime_str: str | None = None
    ) -> tzinfo | None:
        """Resolve OPNsense timezone only when it can be determined.

        Args:
            datetime_str (str | None, optional): Datetime string from OPNsense to
                parse instead of reading the system-time endpoint.

        Returns:
            tzinfo | None: Resolved firewall timezone, or ``None`` when the
                timezone cannot be resolved.
        """
        if datetime_str is None:
            try:
                time_outcome = await self._fetch_endpoint_outcome(SYSTEM_TIME_ENDPOINT)
                if not time_outcome.is_data:
                    _LOGGER.debug("System time endpoint unavailable for timezone resolution")
                    return None
                datetime_payload = time_outcome.mapping()
            except (OPNsenseError, aiohttp.ClientError, TimeoutError) as err:
                _LOGGER.debug(
                    "Failed to access OPNsense system time for timezone resolution: %s: %s",
                    type(err).__name__,
                    err,
                )
                return None
            datetime_value = datetime_payload.get("datetime")
            datetime_str = datetime_value if isinstance(datetime_value, str) else None

        return self._parse_opnsense_tz(datetime_str)

    async def _get_opnsense_timezone(self, datetime_str: str | None = None) -> tzinfo:
        """Resolve timezone information from OPNsense system time data.

        Args:
            datetime_str (str | None, optional): Datetime string parsed from API output.

        Returns:
            tzinfo: Resolved timezone object for OPNsense system data.
        """
        return (
            await self._get_resolved_opnsense_timezone(datetime_str) or self._get_local_timezone()
        )

    @_log_errors
    async def get_device_unique_id(self, expected_id: str | None = None) -> str | None:
        """Return the stable device identifier derived from physical MAC addresses.

        Args:
            expected_id (str | None, optional): Previously known identifier to
                prefer when it is still present among physical interface MAC
                addresses.

        Returns:
            str | None: MAC-address-based identifier with colons replaced by
                underscores. Returns ``expected_id`` when it still matches a
                physical interface, otherwise the first sorted physical MAC
                identifier. Returns ``None`` when no physical MAC addresses are
                available and ``throw_errors`` is disabled.
        """
        interfaces_outcome = await self._fetch_endpoint_outcome(INTERFACE_OVERVIEW_EXPORT_ENDPOINT)
        if not interfaces_outcome.is_data:
            _LOGGER.debug("Interface overview endpoint unavailable for device id resolution")
            self._handle_missing_device_unique_id()
            return None
        instances = interfaces_outcome.sequence()
        mac_addresses: set[str] = set()
        for item in instances:
            if not isinstance(item, MutableMapping):
                continue
            mac = item.get("macaddr_hw")
            if item.get("is_physical") and isinstance(mac, str) and mac:
                mac_addresses.add(mac.replace(":", "_").strip())

        if not mac_addresses:
            _LOGGER.debug("[get_device_unique_id] device_unique_id: None")
            self._handle_missing_device_unique_id()
            return None

        if expected_id and expected_id in mac_addresses:
            _LOGGER.debug(
                "[get_device_unique_id] device_unique_id (matched expected): %s", expected_id
            )
            return expected_id

        device_unique_id = min(mac_addresses)
        _LOGGER.debug("[get_device_unique_id] device_unique_id (first): %s", device_unique_id)
        return device_unique_id

    @_log_errors
    async def get_system_info(self) -> dict[str, Any]:
        """Return basic OPNsense system identity information.

        Returns:
            dict[str, Any]: Mapping containing the OPNsense host ``name`` when
                the system-information endpoint is available.
        """
        system_information_outcome = await self._fetch_endpoint_outcome(SYSTEM_INFORMATION_ENDPOINT)
        if not system_information_outcome.is_data:
            _LOGGER.debug("System information endpoint unavailable")
            return {}
        response = system_information_outcome.mapping()
        return {"name": response.get("name", None)}

    @_log_errors
    async def get_carp(self) -> dict[str, Any] | None:
        """Fetch one CARP snapshot and return both interfaces and aggregate summary.

        Returns:
            dict[str, Any] | None: Snapshot payload containing ``interfaces`` and
                ``status_summary`` derived from one backend fetch, reporting its
                access level through ``result_access()``. The VIP inventory comes
                from the VIP status endpoint at both levels. A forbidden (403) VIP
                settings endpoint, including a cached 403, reports Status Access
                and omits the settings enrichment of each VIP (fields such as
                ``descr`` and ``subnet_bits`` that the status rows lack). Settings
                data, a known missing (404) settings endpoint or a transient
                settings failure reports Configuration Access, the last two with
                status-only VIP data. Returns ``None`` in either error mode when
                the VIP status ``rows`` are missing or malformed, because the VIP
                inventory is then unknown. With the default ``throw_errors=False``,
                also returns ``None`` when the VIP status endpoint is unavailable. When
                ``self._throw_errors`` is ``True``, a failed status or settings
                request raises ``OPNsenseError`` instead, status first,
                specifically ``OPNsensePrivilegeMissing`` for a forbidden (403)
                endpoint; a known missing (404) settings endpoint still reports
                Configuration Access.
        """
        snapshot = await self._fetch_and_merge_carp_vips()
        if snapshot is None:
            return None
        response, vips, access = snapshot
        return AccessDict(
            {
                "interfaces": vips,
                "status_summary": self._build_carp_status_summary(response=response, vips=vips),
            },
            access=access,
        )

    async def _fetch_and_merge_carp_vips(
        self,
    ) -> tuple[dict[str, Any], list[dict[str, Any]], Access] | None:
        """Fetch CARP status/settings and return merged normalized VIP rows.

        Returns:
            tuple[dict[str, Any], list[dict[str, Any]], Access] | None: Raw VIP
                status response, merged/normalized CARP VIP rows derived from status
                + settings endpoints, and the detected access level. ``None`` when
                the VIP status endpoint is unavailable or its ``rows`` are missing
                or malformed.
        """
        vip_status_outcome = await self._fetch_endpoint_outcome(CARP_VIP_STATUS_ENDPOINT)
        if not vip_status_outcome.is_data:
            _LOGGER.debug("CARP VIP status endpoint unavailable")
            return None
        vip_status = vip_status_outcome.mapping()
        vip_status_rows = vip_status.get("rows")
        if not isinstance(vip_status_rows, list):
            _LOGGER.debug("CARP VIP status unavailable (missing or malformed rows)")
            return None
        vip_settings_outcome = await self._fetch_endpoint_outcome(VIP_SETTINGS_ENDPOINT)
        # Only a definitive denial establishes Status Access; a 404 or transient failure does not.
        access = Access.STATUS if vip_settings_outcome.http_status == 403 else Access.CONFIGURATION
        if not vip_settings_outcome.is_data:
            _LOGGER.debug(
                "CARP VIP settings endpoint unavailable; using status-only VIP data (%s access)",
                access,
            )
        vip_settings = vip_settings_outcome.mapping()

        vip_settings_rows = vip_settings.get("rows")
        merged_vips = self._merge_carp_vip_rows(
            vip_status_rows,
            vip_settings_rows if isinstance(vip_settings_rows, list) else [],
        )
        return vip_status, merged_vips, access

    def _build_carp_status_summary(
        self,
        response: dict[str, Any],
        vips: list[dict[str, Any]],
    ) -> dict[str, Any]:
        """Build aggregate CARP status summary using one merged VIP snapshot.

        Args:
            response (dict[str, Any]): Raw response from ``get_vip_status`` endpoint.
            vips (list[dict[str, Any]]): Merged/normalized CARP VIP rows.

        Returns:
            dict[str, Any]: Aggregate CARP health/status payload for Home Assistant sensors.
        """
        summary: dict[str, Any] = {
            "state": "unknown",
            "enabled": False,
            "maintenance_mode": False,
            "demotion": 0,
            "status_message": "",
            "vip_count": 0,
            "master_count": 0,
            "backup_count": 0,
            "other_count": 0,
            "interfaces": [],
            "vips": [],
        }
        carp_raw = response.get("carp")
        if isinstance(carp_raw, Mapping):
            has_carp_block = True
            carp_block: dict[str, Any] = dict(carp_raw)
        else:
            has_carp_block = False
            carp_block = {}
        has_rows = bool(vips)

        enabled = coerce_bool(carp_block.get("allow")) if has_carp_block else bool(vips)
        maintenance_mode = (
            coerce_bool(carp_block.get("maintenancemode")) if has_carp_block else False
        )
        demotion_raw = try_to_int(carp_block.get("demotion"), 0) if has_carp_block else 0
        demotion = demotion_raw if isinstance(demotion_raw, int) else 0
        status_message_raw = carp_block.get("status_msg", "") if has_carp_block else ""
        status_message = (
            status_message_raw.strip()
            if isinstance(status_message_raw, str) and status_message_raw.strip()
            else ""
        )
        master_count = 0
        backup_count = 0
        other_count = 0
        interfaces: set[str] = set()
        for vip in vips:
            status = str(vip.get("status", "")).strip().upper()
            if status == "MASTER":
                master_count += 1
            elif status == "BACKUP":
                backup_count += 1
            else:
                other_count += 1
            interface_name = vip.get("interface")
            if isinstance(interface_name, str) and interface_name.strip():
                interfaces.add(interface_name.strip())

        vip_count = len(vips)
        state = self._classify_carp_state(
            has_carp_block=has_carp_block,
            has_rows=has_rows,
            enabled=enabled,
            maintenance_mode=maintenance_mode,
            vip_count=vip_count,
            demotion=demotion,
            status_message=status_message,
            other_count=other_count,
        )

        summary.update(
            {
                "state": state,
                "enabled": enabled,
                "maintenance_mode": maintenance_mode,
                "demotion": demotion,
                "status_message": status_message,
                "vip_count": vip_count,
                "master_count": master_count,
                "backup_count": backup_count,
                "other_count": other_count,
                "interfaces": sorted(interfaces),
                "vips": vips,
            }
        )
        return summary

    @_log_errors
    async def system_reboot(self) -> bool:
        """Reboot OPNsense.

        Returns:
            bool: True when the operation succeeds; otherwise, False.
        """
        response = await self._safe_dict_post(CORE_SYSTEM_REBOOT_ENDPOINT)
        _LOGGER.debug("[system_reboot] response: %s", response)
        return response.get("status", "") == "ok"

    @_log_errors
    async def system_halt(self) -> None:
        """Shutdown OPNsense."""
        response = await self._safe_dict_post(CORE_SYSTEM_HALT_ENDPOINT)
        _LOGGER.debug("[system_halt] response: %s", response)
        if response.get("status", "") == "ok":
            return
        return

    @_log_errors
    async def toggle_carp_maintenance_mode(self) -> bool:
        """Toggle persistent CARP maintenance mode.

        Returns:
            bool: True when the operation succeeds; otherwise, False.
        """
        # Resolve explicitly: the path is compared with the snake_case spelling before the
        # second capability is asked, so the capability order must be preserved.
        carp_status_endpoint = await self._resolve_endpoint(CARP_STATUS_ENDPOINT)
        if (
            carp_status_endpoint == CARP_STATUS_ENDPOINT.snake_case
            and await self._firmware_capability_enabled(NEW_CARP_STATUS_ENDPOINT_CAPABILITY)
        ):
            carp_status_endpoint = CARP_STATUS_26_1_11_SNAKE_ENDPOINT
        response = await self._safe_dict_post(
            f"{carp_status_endpoint}{CARP_MAINTENANCE_ENDPOINT_SUFFIX}"
        )
        _LOGGER.debug("[toggle_carp_maintenance_mode] response: %s", response)
        return str(response.get("status", "")).lower() == "ok"

    @_log_errors
    async def send_wol(self, interface: str, mac: str) -> bool:
        """Send a wake on lan packet to the specified MAC address.

        Args:
            interface (str): OPNsense interface identifier used as the
                Wake-on-LAN egress interface.
            mac (str): MAC address to use for Wake-on-LAN.

        Returns:
            bool: True when the operation succeeds; otherwise, False.
        """
        payload: dict[str, Any] = {"wake": {"interface": interface, "mac": mac}}
        _LOGGER.debug("[send_wol] payload: %s", payload)
        response = await self._safe_dict_post(WOL_SET_ENDPOINT, payload)
        _LOGGER.debug("[send_wol] response: %s", response)
        return response.get("status", "") == "ok"

    @_log_errors
    async def get_notices(self) -> dict[str, Any]:
        """Return active OPNsense dashboard notices.

        Returns:
            dict[str, Any]: Mapping with ``pending_notices_present`` and a
                ``pending_notices`` list. Each notice includes its message,
                subject ``id``, and parsed ``created_at`` timestamp when
                available.
        """
        status_outcome = await self._fetch_endpoint_outcome(CORE_SYSTEM_STATUS_ENDPOINT)
        if not status_outcome.is_data:
            _LOGGER.debug("System status endpoint unavailable for notices")
            return {
                "pending_notices_present": False,
                "pending_notices": [],
            }

        notices_info = status_outcome.mapping()
        pending_notices_present = False
        pending_notices: list = []
        for key, notice in notices_info.items():
            if isinstance(notice, MutableMapping) and notice.get("statusCode", 2) != 2:
                pending_notices_present = True
                pending_notices.append(
                    {
                        "notice": notice.get("message", None),
                        "id": key,
                        "created_at": timestamp_to_datetime(
                            try_to_int(notice.get("timestamp", None))
                        ),
                    }
                )

        return {
            "pending_notices_present": pending_notices_present,
            "pending_notices": pending_notices,
        }

    @_log_errors
    async def close_notice(self, id: str) -> bool:
        """Close selected notices.

        Args:
            id (str): Identifier of the notice to close.

        Returns:
            bool: True when the operation succeeds; otherwise, False.
        """
        # Resolve once and reuse the path across the POST loop below.
        dismiss_endpoint = await self._resolve_endpoint(CORE_SYSTEM_DISMISS_ENDPOINT)

        # id = "all" to close all notices
        success = True
        if id.lower() == "all":
            status_outcome = await self._fetch_endpoint_outcome(CORE_SYSTEM_STATUS_ENDPOINT)
            if not status_outcome.is_data:
                _LOGGER.debug("System status endpoint unavailable for closing notices")
                return False
            notices = status_outcome.mapping()
            for key, notice in notices.items():
                if not isinstance(notice, MutableMapping):
                    continue
                if notice.get("statusCode", 2) != 2:
                    dismiss = await self._safe_dict_post(dismiss_endpoint, payload={"subject": key})
                    if dismiss.get("status", "failed") != "ok":
                        success = False
        else:
            dismiss = await self._safe_dict_post(dismiss_endpoint, payload={"subject": id})
            _LOGGER.debug("[close_notice] id: %s, dismiss: %s", id, dismiss)
            if dismiss.get("status", "failed") != "ok":
                success = False
        _LOGGER.debug("[close_notice] success: %s", success)
        return success

    @_log_errors
    async def reload_interface(self, if_name: str) -> bool:
        """Reload the specified interface.

        Args:
            if_name (str): Interface name to select rows for.

        Returns:
            bool: True when the operation succeeds; otherwise, False.
        """
        reload_endpoint = await self._resolve_endpoint(
            INTERFACE_OVERVIEW_RELOAD_ENDPOINT_PREFIX.with_suffix(if_name)
        )
        reload = await self._safe_dict_post(reload_endpoint)
        return reload.get("message", "").startswith("OK")

    @_log_errors
    async def get_certificates(self) -> dict[str, Any]:
        """Return trust certificates known to OPNsense.

        Returns:
            dict[str, Any]: Mapping keyed by certificate description. Each
                certificate contains its UUID, issuer reference, RFC 3280
                purpose, in-use flag, and validity timestamps.
        """
        certs_outcome = await self._fetch_endpoint_outcome(CERT_SEARCH_ENDPOINT)
        if not certs_outcome.is_data:
            _LOGGER.debug("Certificate search endpoint unavailable")
            return {}

        certs_raw = certs_outcome.mapping()
        cert_rows = certs_raw.get("rows")
        if not isinstance(cert_rows, list):
            return {}
        certs: dict[str, Any] = {}
        for cert in cert_rows:
            if cert.get("descr", None):
                certs[cert.get("descr")] = {
                    "uuid": cert.get("uuid", None),
                    "issuer": cert.get("caref", None),
                    "purpose": cert.get("rfc3280_purpose", None),
                    "in_use": api_value_matches(cert.get("in_use", "0"), "1"),
                    "valid_from": timestamp_to_datetime(try_to_int(cert.get("valid_from", None))),
                    "valid_to": timestamp_to_datetime(try_to_int(cert.get("valid_to", None))),
                }
        _LOGGER.debug("[get_certificates] certs length: %s", len(certs))
        return certs