from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from armorer.core import _start_optional_messaging_bridges


@patch("armorer.core.Thread")
@patch("armorer.core.TelegramCoreBridge")
@patch("armorer.core.TelegramGateway")
@patch("armorer.core.InboxOutboxRelay")
@patch("armorer.core.ConfigManager")
def test_start_optional_messaging_bridges_starts_telegram_when_configured(
    mock_config_cls,
    mock_relay_cls,
    mock_gateway_cls,
    mock_bridge_cls,
    mock_thread_cls,
    monkeypatch,
    tmp_path: Path,
):
    monkeypatch.setenv("ARMORER_TELEGRAM_BOT_TOKEN", "123:abc")
    cfg = MagicMock()
    cfg.get_armorer_telegram_bot_token.return_value = ""
    cfg.get_key.return_value = ""
    mock_config_cls.return_value = cfg
    mock_thread = MagicMock()
    mock_thread_cls.return_value = mock_thread

    threads = _start_optional_messaging_bridges(tmp_path)

    mock_relay_cls.assert_called_once_with(config_dir=tmp_path)
    mock_gateway_cls.assert_called_once_with(bot_token="123:abc")
    mock_bridge_cls.assert_called_once()
    mock_thread.start.assert_called_once()
    assert threads == [mock_thread]


@patch("armorer.core.Thread")
@patch("armorer.core.SignalCoreBridge")
@patch("armorer.core.SignalGateway")
@patch("armorer.core.TelegramCoreBridge")
@patch("armorer.core.TelegramGateway")
@patch("armorer.core.InboxOutboxRelay")
@patch("armorer.core.ConfigManager")
def test_start_optional_messaging_bridges_skips_when_unconfigured(
    mock_config_cls,
    mock_relay_cls,
    mock_tg_gateway_cls,
    mock_tg_bridge_cls,
    mock_signal_gateway_cls,
    mock_signal_bridge_cls,
    mock_thread_cls,
    monkeypatch,
    tmp_path: Path,
):
    monkeypatch.delenv("ARMORER_TELEGRAM_BOT_TOKEN", raising=False)
    monkeypatch.delenv("ARMORER_SIGNAL_ACCOUNT", raising=False)
    cfg = MagicMock()
    cfg.get_armorer_telegram_bot_token.return_value = ""

    def get_key(name: str):
        return ""

    cfg.get_key.side_effect = get_key
    mock_config_cls.return_value = cfg

    threads = _start_optional_messaging_bridges(tmp_path)

    mock_relay_cls.assert_called_once_with(config_dir=tmp_path)
    mock_tg_gateway_cls.assert_not_called()
    mock_tg_bridge_cls.assert_not_called()
    mock_signal_gateway_cls.assert_not_called()
    mock_signal_bridge_cls.assert_not_called()
    mock_thread_cls.assert_not_called()
    assert threads == []
