import json
import logging

from spade.agent import Message
from spade.behaviour import CyclicBehaviour
from spade_bdi.bdi import BDIAgent

from control_backend.core.config import settings


class BeliefSetterBehaviour(CyclicBehaviour):
    """
    This is the behaviour that the BDI agent runs. This behaviour waits for incoming
    message and processes it based on sender.
    """

    agent: BDIAgent
    logger = logging.getLogger("BDI/Belief Setter")

    async def run(self):
        msg = await self.receive(timeout=0.1)
        if msg:
            self.logger.info(f"Received message {msg.body}")
            self._process_message(msg)

    def _process_message(self, message: Message):
        sender = message.sender.node  # removes host from jid and converts to str
        self.logger.debug("Sender: %s", sender)

        match sender:
            case settings.agent_settings.belief_collector_agent_name:
                self.logger.debug("Processing message from belief collector.")
                self._process_belief_message(message)
            case _:
                self.logger.debug("Not the belief agent, discarding message")
                pass

    def _process_belief_message(self, message: Message):
        if not message.body:
            return

        match message.thread:
            case "beliefs":
                try:
                    beliefs: dict[str, list[str]] = json.loads(message.body)
                    self._set_beliefs(beliefs)
                except json.JSONDecodeError as e:
                    self.logger.error("Could not decode beliefs into JSON format: %s", e)
            case _:
                pass

    def _set_beliefs(self, beliefs: dict[str, list[str]]):
        """Remove previous values for beliefs and update them with the provided values."""
        if self.agent.bdi is None:
            self.logger.warning("Cannot set beliefs, since agent's BDI is not yet initialized.")
            return

        # Set new beliefs (outdated beliefs are automatically removed)
        for belief, arguments in beliefs.items():
            self.agent.bdi.set_belief(belief, *arguments)

            # Special case: if there's a new user message, flag that we haven't responded yet
            if belief == "user_said":
                self.agent.bdi.set_belief("new_message")

            self.logger.info("Set belief %s with arguments %s", belief, arguments)
