import sys
from unittest.mock import MagicMock


def pytest_configure(config):
    """
    This hook runs at the start of the pytest session, before any tests are
    collected. It mocks heavy or unavailable modules to prevent ImportErrors.
    """
    # --- Mock spade and spade-bdi ---
    mock_spade = MagicMock()
    mock_spade.agent = MagicMock()
    mock_spade.behaviour = MagicMock()
    mock_spade.message = MagicMock()
    mock_spade_bdi = MagicMock()
    mock_spade_bdi.bdi = MagicMock()

    mock_spade.agent.Message = MagicMock()
    mock_spade.behaviour.CyclicBehaviour = type("CyclicBehaviour", (object,), {})
    mock_spade_bdi.bdi.BDIAgent = type("BDIAgent", (object,), {})

    sys.modules["spade"] = mock_spade
    sys.modules["spade.agent"] = mock_spade.agent
    sys.modules["spade.behaviour"] = mock_spade.behaviour
    sys.modules["spade.message"] = mock_spade.message
    sys.modules["spade_bdi"] = mock_spade_bdi
    sys.modules["spade_bdi.bdi"] = mock_spade_bdi.bdi

    # --- Mock the config module to prevent Pydantic ImportError ---
    mock_config_module = MagicMock()

    # The code under test does `from ... import settings`, so our mock module
    # must have a `settings` attribute. We'll make it a MagicMock so we can
    # configure it later in our tests using mocker.patch.
    mock_config_module.settings = MagicMock()

    sys.modules["control_backend.core.config"] = mock_config_module

    # --- Mock torch and zmq for VAD ---
    mock_torch = MagicMock()
    mock_zmq = MagicMock()
    mock_zmq.asyncio = mock_zmq

    # In individual tests, these can be imported and the return values changed
    sys.modules["torch"] = mock_torch
    sys.modules["zmq"] = mock_zmq
    sys.modules["zmq.asyncio"] = mock_zmq.asyncio

    # --- Mock whisper ---
    mock_whisper = MagicMock()
    mock_mlx = MagicMock()
    mock_mlx.core = MagicMock()
    mock_mlx_whisper = MagicMock()
    mock_mlx_whisper.transcribe = MagicMock()

    sys.modules["whisper"] = mock_whisper
    sys.modules["mlx"] = mock_mlx
    sys.modules["mlx.core"] = mock_mlx
    sys.modules["mlx_whisper"] = mock_mlx_whisper
    sys.modules["mlx_whisper.transcribe"] = mock_mlx_whisper.transcribe
