from logging import getLogger

from defence360agent.rpc_tools.lookup import bind
from defence360agent.utils import Scope
from imav.simple_rpc.conflicts import (
    ConflictsEndpoints as ConflictsEndpointsAV,
)
from im360.internals.core.firewall import is_nat_available
from im360.subsys import csf
from im360.subsys.panels.generic import GenericPanel
from im360.subsys.panels.hosting_panel import HostingPanel
from im360.subsys.panels import hosting_panel
from im360.subsys.running_ids import RunningIds
from im360.subsys.webshield import is_ssl_cache_configured
from im360.subsys.pam import enable, PAMError, PamService
from im360.subsys.smtp_blocking import is_SMTP_blocking_supported
from im360.subsys.waf_rules_configurator import is_webserver_supported
from defence360agent.utils.validate import IP

logger = getLogger(__name__)


class ConflictsEndpoints(ConflictsEndpointsAV):
    """Imunify360 3rdparty endpoints

    Endpoints:
     - 3rdparty conflicts (defined in the base class)
     - 3rdparty list
    """

    SCOPE = Scope.IM360

    @bind("3rdparty", "list")
    async def list_3rdparty_cmd(self):
        return {"items": (await RunningIds()).ids_list}

    @property
    def _funcs(self):
        """List of functions for "3rdparty conflicts" endpoint"""

        return super()._funcs + [
            self._malware_scan_conflicts,
            self._csf_conflicts,
            self._smtp_blocking_conflicts,
            self._waf_conflicts,
            self._webshield_ssl_conflicts,
            self._pam_ftp_conflicts,
        ]

    @staticmethod
    async def _malware_scan_conflicts(results_dict):
        if not await HostingPanel().installed_modsec():
            results_dict["scan_modsec"] = True

        return results_dict

    @staticmethod
    async def _csf_conflicts(results_dict):
        if await csf.is_running():
            results_dict["csf_dos_protector"] = True
        return results_dict

    @staticmethod
    async def _smtp_blocking_conflicts(results_dict):
        if not await is_SMTP_blocking_supported():
            results_dict["smtp_blocking_kernel_support"] = True
        if await csf.is_SMTP_block_enabled():
            results_dict["smtp_blocking_CSF_block"] = True
        is_hp_has_SMTP_conflict = HostingPanel().get_SMTP_conflict_status()
        if is_hp_has_SMTP_conflict:
            results_dict["smtp_blocking_enable"] = True
        if not is_nat_available(IP.V6):
            results_dict["smtp_blocking_ip6table_nat"] = True
        return results_dict

    @staticmethod
    async def _waf_conflicts(results_dict):
        if not await is_webserver_supported():
            results_dict["mod_sec_app_specific_ruleset_apache_v24"] = True
        return results_dict

    @staticmethod
    async def _webshield_ssl_conflicts(results_dict):
        panel = hosting_panel.HostingPanel()
        if (
            isinstance(panel, GenericPanel)
            and not await is_ssl_cache_configured()
        ):
            results_dict["webshield_ssl_cache_not_configured"] = True
        return results_dict

    @staticmethod
    async def _pam_ftp_conflicts(results_dict):
        try:
            await enable(PamService.FTP, True)
        except PAMError:
            results_dict["pam_ftp_not_available"] = True
