from pathlib import Path
from typing import NamedTuple, Optional

STATE_PATH = Path("/var/run/imunify360/firewall-backend")
_MAX_SIZE = 4096
_BACKENDS = ("iptables", "nftables")


class BackendState(NamedTuple):
    active: str = "iptables"
    target: str = ""
    reason: str = "unknown"


def read_backend_state(path: Path = STATE_PATH) -> BackendState:
    try:
        with open(path, "rb") as state:
            content = state.read(_MAX_SIZE + 1)
        if len(content) > _MAX_SIZE:
            return BackendState()
        lines = content.decode("utf-8").splitlines()
    except (OSError, ValueError):
        return BackendState()
    fields = {}
    for line in lines:
        key, sep, value = line.partition("=")
        if sep:
            fields[key.strip()] = value.strip()
    active = fields.get("active")
    if active not in _BACKENDS:
        return BackendState()
    target = fields.get("target", "")
    return BackendState(
        active=active,
        target=target if target in _BACKENDS else "",
        reason=fields.get("reason") or "unknown",
    )


# The resident re-decides after a config update, so only a reason that a new
# FIREWALL.backend cannot change is worth a warning: the kill switch, or a
# probe that already found nftables unusable here.
def nftables_kept_as_intent_warning(
    data: dict, state: BackendState
) -> Optional[str]:
    section = data.get("FIREWALL")
    requested = section.get("backend") if isinstance(section, dict) else None
    if not isinstance(requested, str):
        return None
    if requested.strip().lower() != "nftables":
        return None
    if state.reason != "kill-switch" and not state.reason.startswith("probe:"):
        return None
    return (
        "FIREWALL.backend is set to nftables, but the server stays on"
        f" iptables (reason: {state.reason}). The setting is kept and"
        " applies once that reason no longer holds."
    )
