"""Resolve firewall binary paths to absolute locations."""

import logging
import os
from functools import lru_cache

logger = logging.getLogger(__name__)

_SEARCH_DIRS = ("/usr/sbin", "/usr/bin", "/sbin", "/bin")


@lru_cache(maxsize=None)
def _find_executable(name: str) -> str:
    """Resolve *name* to an absolute path by checking well-known directories
    first, then ``$PATH``.  Returns the bare *name* as a fallback."""
    for dir_ in _SEARCH_DIRS:
        path = os.path.join(dir_, name)
        if os.path.isfile(path) and os.access(path, os.X_OK):
            return path
    for dir_ in os.environ.get("PATH", "").split(os.pathsep):
        if not dir_:
            continue
        path = os.path.join(dir_, name)
        if os.path.isfile(path) and os.access(path, os.X_OK):
            return path
    logger.error(
        "Cannot find executable '%s' in PATH %s",
        name,
        os.environ.get("PATH"),
    )
    return name


def get_iptables_exe():
    return _find_executable("iptables")


def get_ip6tables_exe():
    return _find_executable("ip6tables")


def get_iptables_restore_exe():
    return _find_executable("iptables-restore")


def get_ip6tables_restore_exe():
    return _find_executable("ip6tables-restore")
