import unittest

import hiveos.config as config_module
import hiveos.services.intent_service as intent_service_module
import hiveos.services.terminal_service as terminal_service_module


class ModelRouteOverrideTests(unittest.TestCase):
    def setUp(self):
        self._orig_default = config_module.AI_ROUTE_MODEL_DEFAULT
        self._orig_localize = config_module.AI_ROUTE_MODEL_LOCALIZE
        self._orig_tutor = config_module.AI_ROUTE_MODEL_TUTOR
        self._orig_hw = config_module.AI_ROUTE_MODEL_HARDWARE_EXPLAINER
        self._orig_intent = config_module.AI_ROUTE_MODEL_INTENT_COMPILE
        self._orig_term_provider = terminal_service_module.AI_PROVIDER
        self._orig_intent_provider = intent_service_module.AI_PROVIDER

    def tearDown(self):
        config_module.AI_ROUTE_MODEL_DEFAULT = self._orig_default
        config_module.AI_ROUTE_MODEL_LOCALIZE = self._orig_localize
        config_module.AI_ROUTE_MODEL_TUTOR = self._orig_tutor
        config_module.AI_ROUTE_MODEL_HARDWARE_EXPLAINER = self._orig_hw
        config_module.AI_ROUTE_MODEL_INTENT_COMPILE = self._orig_intent
        terminal_service_module.AI_PROVIDER = self._orig_term_provider
        intent_service_module.AI_PROVIDER = self._orig_intent_provider

    def test_get_ai_route_model_prefers_route_specific_override(self):
        config_module.AI_ROUTE_MODEL_DEFAULT = "default-model"
        config_module.AI_ROUTE_MODEL_LOCALIZE = "localize-model"
        selected = config_module.get_ai_route_model("localize", fallback_model="fallback-model")
        self.assertEqual("localize-model", selected)

    def test_get_ai_route_model_uses_default_then_fallback(self):
        config_module.AI_ROUTE_MODEL_DEFAULT = "default-model"
        config_module.AI_ROUTE_MODEL_LOCALIZE = ""
        selected = config_module.get_ai_route_model("localize", fallback_model="fallback-model")
        self.assertEqual("default-model", selected)

        config_module.AI_ROUTE_MODEL_DEFAULT = ""
        selected = config_module.get_ai_route_model("localize", fallback_model="fallback-model")
        self.assertEqual("fallback-model", selected)

    def test_services_emit_route_specific_model_names(self):
        config_module.AI_ROUTE_MODEL_LOCALIZE = "route-localize-model"
        config_module.AI_ROUTE_MODEL_INTENT_COMPILE = "route-intent-model"
        terminal_service_module.AI_PROVIDER = "ollama"
        intent_service_module.AI_PROVIDER = "ollama"

        terminal_meta = terminal_service_module._transform_model_meta("localize")
        self.assertEqual("ollama", terminal_meta.get("provider"))
        self.assertEqual("route-localize-model", terminal_meta.get("name"))

        intent_meta = intent_service_module._intent_trace_model(use_model=True)
        self.assertEqual("ollama", intent_meta.get("provider"))
        self.assertEqual("route-intent-model", intent_meta.get("name"))


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