"""
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.


This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.


You should have received a copy of the GNU General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.

Copyright © 2019 Cloud Linux Software Inc.

This software is also available under ImunifyAV commercial license,
see <https://www.imunify360.com/legal/eula>
"""
import logging

from defence360agent.contracts.config import SystemConfig
from defence360agent.contracts.messages import ConfigUpdate
from defence360agent.contracts.plugins import MessageSink, expect
from defence360agent.utils import LazyLock, Scope
from imav.contracts.config import Malware as MalwareConfig
from imav.malwarelib.subsys import aibolit
from imav.malwarelib.subsys.malware import HackerTrapHitsSaver

logger = logging.getLogger(__name__)


class DetectAdminToolsWatcher(MessageSink):
    SCOPE = Scope.IM360
    # Must be a class attribute — LazyLock is a descriptor whose
    # ``__get__`` is only invoked for class-level access. Without the
    # lock, two ConfigUpdate messages in the same event-loop tick can
    # read the same ``_previous_detect_admin_tools`` snapshot and fire
    # the resync in the wrong order. See DEF-38724.
    _lock = LazyLock()

    def __init__(self):
        self._previous_detect_admin_tools = MalwareConfig.DETECT_ADMIN_TOOLS

    async def create_sink(self, loop) -> None:
        # Boot-time rebuild owned by ``StartupActions.reset_sa_hits``
        # (which honours DETECT_ADMIN_TOOLS via the SQL filter).
        pass

    @expect(ConfigUpdate)
    async def on_config_update(self, message: ConfigUpdate):
        if not isinstance(message["conf"], SystemConfig):
            return
        async with self._lock:
            current_value = MalwareConfig.DETECT_ADMIN_TOOLS
            if self._previous_detect_admin_tools == current_value:
                return
            logger.info(
                "DETECT_ADMIN_TOOLS changed from %s to %s, restarting"
                " ai-bolit",
                self._previous_detect_admin_tools,
                current_value,
            )
            self._previous_detect_admin_tools = current_value
            await aibolit.restart_on_detect_admin_tools_update()
            await HackerTrapHitsSaver.reset_sa_hits()
