import os
import sys
import types
import unittest
from unittest.mock import patch

if "paho.mqtt.client" not in sys.modules:
    paho_mod = types.ModuleType("paho")
    mqtt_mod = types.ModuleType("paho.mqtt")
    client_mod = types.ModuleType("paho.mqtt.client")

    class _DummyClient:
        def __init__(self, *args, **kwargs):
            pass

        def username_pw_set(self, *args, **kwargs):
            pass

        def connect(self, *args, **kwargs):
            pass

        def loop_start(self):
            pass

        def loop_stop(self):
            pass

        def disconnect(self):
            pass

    client_mod.Client = _DummyClient
    mqtt_mod.client = client_mod
    paho_mod.mqtt = mqtt_mod
    sys.modules["paho"] = paho_mod
    sys.modules["paho.mqtt"] = mqtt_mod
    sys.modules["paho.mqtt.client"] = client_mod

from missioncontrol_mcp import server


class ServerConfigTests(unittest.TestCase):
    def test_base_urls_uses_fallback_list(self):
        with patch.dict(
            os.environ,
            {
                "MISSIONCONTROL_BASE_URLS": "https://a.example, https://b.example ,http://localhost:8008",
                "MISSIONCONTROL_BASE_URL": "https://ignored.example",
            },
            clear=False,
        ):
            self.assertEqual(
                server.base_urls(),
                ["https://a.example", "https://b.example", "http://localhost:8008"],
            )

    def test_base_urls_falls_back_to_single_base_url(self):
        with patch.dict(
            os.environ,
            {"MISSIONCONTROL_BASE_URLS": "", "MISSIONCONTROL_BASE_URL": "https://single.example"},
            clear=False,
        ):
            self.assertEqual(server.base_urls(), ["https://single.example"])

    def test_preflight_mode_defaults_on_invalid(self):
        with patch.dict(os.environ, {"MISSIONCONTROL_STARTUP_PREFLIGHT": "invalid"}, clear=False):
            self.assertEqual(server._preflight_mode(), "health")

    def test_parse_bool_env(self):
        with patch.dict(os.environ, {"MISSIONCONTROL_FAIL_OPEN_ON_LIST": "true"}, clear=False):
            self.assertTrue(server.parse_bool_env("MISSIONCONTROL_FAIL_OPEN_ON_LIST", False))
        with patch.dict(os.environ, {"MISSIONCONTROL_FAIL_OPEN_ON_LIST": "0"}, clear=False):
            self.assertFalse(server.parse_bool_env("MISSIONCONTROL_FAIL_OPEN_ON_LIST", True))

    def test_http_json_helper_uses_client(self):
        class _Client:
            def http_json(self, method, path, payload=None):
                return {"method": method, "path": path, "payload": payload}

        with patch.object(server, "_HTTP_CLIENT_SINGLETON", _Client()):
            out = server.http_json("GET", "/explorer/tree")
        self.assertEqual(out["method"], "GET")
        self.assertEqual(out["path"], "/explorer/tree")


if __name__ == "__main__":
    unittest.main()
