import json

from control_backend.agents.base import BaseAgent
from control_backend.core.agent_system import InternalMessage
from control_backend.core.config import settings


class TextBeliefExtractorAgent(BaseAgent):
    """
    Text Belief Extractor Agent.

    This agent is responsible for processing raw text (e.g., from speech transcription) and
    extracting semantic beliefs from it.

    In the current demonstration version, it performs a simple wrapping of the user's input
    into a ``user_said`` belief. In a full implementation, this agent would likely interact
    with an LLM or NLU engine to extract intent, entities, and other structured information.
    """

    async def setup(self):
        """
        Initialize the agent and its resources.
        """
        self.logger.info("Settting up %s.", self.name)
        # Setup LLM belief context if needed (currently demo is just passthrough)
        self.beliefs = {"mood": ["X"], "car": ["Y"]}

    async def handle_message(self, msg: InternalMessage):
        """
        Handle incoming messages, primarily from the Transcription Agent.

        :param msg: The received message containing transcribed text.
        """
        sender = msg.sender
        if sender == settings.agent_settings.transcription_name:
            self.logger.debug("Received text from transcriber: %s", msg.body)
            await self._process_transcription_demo(msg.body)
        else:
            self.logger.info("Discarding message from %s", sender)

    async def _process_transcription_demo(self, txt: str):
        """
        Process the transcribed text and generate beliefs.

        **Demo Implementation:**
        Currently, this method takes the raw text ``txt`` and wraps it into a belief structure:
        ``user_said("txt")``.

        This belief is then sent to the :class:`BDIBeliefCollectorAgent`.

        :param txt: The raw transcribed text string.
        """
        # For demo, just wrapping user text as user_said belief
        belief = {"beliefs": {"user_said": [txt]}, "type": "belief_extraction_text"}
        payload = json.dumps(belief)

        belief_msg = InternalMessage(
            to=settings.agent_settings.bdi_belief_collector_name,
            sender=self.name,
            body=payload,
            thread="beliefs",
        )

        await self.send(belief_msg)
        self.logger.info("Sent %d beliefs to the belief collector.", len(belief["beliefs"]))
