"""
Tests for missing coverage gaps in local_deep_research/config/llm_config.py.

Targets specific uncovered code paths:
- get_llm env var logic (LDR_USE_FALLBACK_LLM, LDR_TESTING_WITH_MOCKS,
  provider_has_config skipping, lmstudio/llamacpp local checks)
- get_llm ollama model-not-found, creation exception (now raises), enable_thinking true/false
- get_llm llamacpp no model path, invalid extension, directory with gguf suggestion
- _get_context_window_for_provider cloud unrestricted=False, local None window
- wrap_llm_without_think_tags context_limit injection, no-overwrite, model_name vs model
"""

import os
from unittest.mock import MagicMock, patch

import pytest

MODULE = "local_deep_research.config.llm_config"


def _settings_dict(overrides=None):
    """Base settings dict with sensible defaults for most tests."""
    base = {
        "llm.model": "test-model",
        "llm.temperature": 0.5,
        "llm.provider": "ollama",
        "llm.local_context_window_size": 4096,
        "llm.context_window_unrestricted": True,
        "llm.supports_max_tokens": True,
        "llm.max_tokens": 4096,
        "rate_limiting.llm_enabled": False,
    }
    if overrides:
        base.update(overrides)
    return base


def _mock_get_setting(settings):
    """Return a side_effect callable that reads from the given dict."""
    return lambda key, default=None, **kw: settings.get(key, default)


class TestGetLlmFallbackEnvVar:
    """Tests for LDR_USE_FALLBACK_LLM / LDR_TESTING_WITH_MOCKS env var guard."""

    def test_fallback_env_var_skipped_when_testing_with_mocks(self):
        """When LDR_TESTING_WITH_MOCKS is set, fallback env var is ignored;
        now raises ValueError since fallback model was removed."""
        settings = _settings_dict({"llm.provider": "none"})
        with (
            patch.dict(
                os.environ,
                {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": "1"},
            ),
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError):
                get_llm(provider="none", settings_snapshot=settings)

    def test_fallback_env_var_with_openai_config_skips_fallback(self):
        """When provider has config (openai with api_key), fallback is NOT used."""
        settings = _settings_dict(
            {"llm.provider": "openai", "llm.openai.api_key": "sk-real-key"}
        )
        mock_openai_cls = MagicMock()
        mock_openai_instance = MagicMock()
        mock_openai_cls.return_value = mock_openai_instance
        with (
            patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
            patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.ChatOpenAI", mock_openai_cls),
            patch(
                f"{MODULE}.wrap_llm_without_think_tags",
                return_value=mock_openai_instance,
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            result = get_llm(provider="openai", settings_snapshot=settings)
            mock_openai_cls.assert_called_once()
            assert result is mock_openai_instance

    def test_fallback_env_var_no_config_raises_error(self):
        """When provider has NO config, ValueError is raised (fallback model removed)."""
        settings = _settings_dict(
            {"llm.provider": "openai", "llm.openai.api_key": None}
        )
        with (
            patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
            patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError):
                get_llm(provider="openai", settings_snapshot=settings)

    def test_fallback_env_var_lmstudio_available_skips_fallback(self):
        """When provider is lmstudio and available, fallback is skipped."""
        settings = _settings_dict({"llm.provider": "lmstudio"})
        mock_openai_cls = MagicMock()
        mock_lmstudio_instance = MagicMock()
        mock_openai_cls.return_value = mock_lmstudio_instance
        with (
            patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
            patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_lmstudio_available", return_value=True),
            patch(f"{MODULE}.normalize_url", side_effect=lambda x: x),
            patch(f"{MODULE}.ChatOpenAI", mock_openai_cls),
            patch(
                f"{MODULE}.wrap_llm_without_think_tags",
                return_value=mock_lmstudio_instance,
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            result = get_llm(provider="lmstudio", settings_snapshot=settings)
            mock_openai_cls.assert_called_once()
            assert result is mock_lmstudio_instance

    def test_fallback_env_var_llamacpp_available_skips_fallback(self):
        """When provider is llamacpp and available, fallback is skipped."""
        settings = _settings_dict(
            {"llm.provider": "llamacpp", "llm.llamacpp_model_path": None}
        )
        with (
            patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
            patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_llamacpp_available", return_value=True),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError, match="model path not configured"):
                get_llm(provider="llamacpp", settings_snapshot=settings)


class TestGetLlmOllamaEdgeCases:
    """Tests for ollama-specific edge cases in get_llm."""

    def _ollama_settings(self, overrides=None):
        s = _settings_dict(
            {
                "llm.provider": "ollama",
                "llm.ollama.url": "http://localhost:11434",
                "llm.ollama.enable_thinking": True,
            }
        )
        if overrides:
            s.update(overrides)
        return s

    def test_ollama_model_not_found_raises_error(self):
        """When model is not in the Ollama model list, ValueError is raised (fallback removed)."""
        settings = self._ollama_settings()
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            "models": [{"name": "llama2"}, {"name": "mistral"}]
        }
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_ollama_available", return_value=True),
            patch(f"{MODULE}.safe_get", return_value=mock_response),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError, match="not found in Ollama"):
                get_llm(
                    provider="ollama",
                    model_name="nonexistent-model",
                    settings_snapshot=settings,
                )

    def test_ollama_creation_exception_raises_error(self):
        """When ChatOllama() raises, exception is propagated (fallback removed)."""
        settings = self._ollama_settings()
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {"models": [{"name": "test-model"}]}
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_ollama_available", return_value=True),
            patch(f"{MODULE}.safe_get", return_value=mock_response),
            patch(
                f"{MODULE}.ChatOllama",
                side_effect=RuntimeError("failed to init"),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(RuntimeError, match="failed to init"):
                get_llm(
                    provider="ollama",
                    model_name="test-model",
                    settings_snapshot=settings,
                )

    def test_ollama_enable_thinking_true_sets_reasoning(self):
        """When enable_thinking is True, reasoning=True is passed to ChatOllama."""
        settings = self._ollama_settings({"llm.ollama.enable_thinking": True})
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {"models": [{"name": "test-model"}]}
        mock_ollama_cls = MagicMock()
        mock_ollama_cls.return_value = MagicMock()
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_ollama_available", return_value=True),
            patch(f"{MODULE}.safe_get", return_value=mock_response),
            patch(f"{MODULE}.ChatOllama", mock_ollama_cls),
            patch(
                f"{MODULE}.wrap_llm_without_think_tags",
                return_value=MagicMock(),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            get_llm(
                provider="ollama",
                model_name="test-model",
                settings_snapshot=settings,
            )
            call_kwargs = mock_ollama_cls.call_args[1]
            assert call_kwargs["reasoning"] is True

    def test_ollama_enable_thinking_false_sets_reasoning_false(self):
        """When enable_thinking is False, reasoning=False is passed to ChatOllama."""
        settings = self._ollama_settings({"llm.ollama.enable_thinking": False})
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {"models": [{"name": "test-model"}]}
        mock_ollama_cls = MagicMock()
        mock_ollama_cls.return_value = MagicMock()
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(f"{MODULE}.is_ollama_available", return_value=True),
            patch(f"{MODULE}.safe_get", return_value=mock_response),
            patch(f"{MODULE}.ChatOllama", mock_ollama_cls),
            patch(
                f"{MODULE}.wrap_llm_without_think_tags",
                return_value=MagicMock(),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            get_llm(
                provider="ollama",
                model_name="test-model",
                settings_snapshot=settings,
            )
            call_kwargs = mock_ollama_cls.call_args[1]
            assert call_kwargs["reasoning"] is False


class TestGetLlmLlamaCppEdgeCases:
    """Tests for llamacpp-specific edge cases in get_llm."""

    def test_llamacpp_no_model_path_raises(self):
        """When llamacpp_model_path is not set, ValueError is raised."""
        settings = _settings_dict(
            {"llm.provider": "llamacpp", "llm.llamacpp_model_path": None}
        )
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError, match="model path not configured"):
                get_llm(provider="llamacpp", settings_snapshot=settings)

    def test_llamacpp_invalid_extension_raises(self, tmp_path):
        """A file with a non-.gguf/.bin extension raises ValueError."""
        bad_file = tmp_path / "model.safetensors"
        bad_file.write_text("not a gguf model")
        settings = _settings_dict(
            {
                "llm.provider": "llamacpp",
                "llm.llamacpp_model_path": str(bad_file),
            }
        )
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(
                "local_deep_research.security.path_validator.PathValidator.validate_model_path",
                return_value=bad_file,
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(
                ValueError, match="Invalid model file extension"
            ):
                get_llm(provider="llamacpp", settings_snapshot=settings)

    def test_llamacpp_directory_with_gguf_suggestion(self, tmp_path):
        """When path is a directory with .gguf files, the error lists them."""
        (tmp_path / "model_a.gguf").write_text("fake")
        (tmp_path / "model_b.gguf").write_text("fake")
        settings = _settings_dict(
            {
                "llm.provider": "llamacpp",
                "llm.llamacpp_model_path": str(tmp_path),
            }
        )
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(
                "local_deep_research.security.path_validator.PathValidator.validate_model_path",
                side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
            ),
            patch(
                "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
                return_value=tmp_path,
            ),
            patch(
                "local_deep_research.config.paths.get_models_directory",
                return_value=tmp_path,
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(
                ValueError, match="Found .gguf files:"
            ) as exc_info:
                get_llm(provider="llamacpp", settings_snapshot=settings)
            msg = str(exc_info.value)
            assert "model_a.gguf" in msg
            assert "model_b.gguf" in msg

    def test_llamacpp_directory_no_gguf_files(self, tmp_path):
        """When path is a directory with no .gguf files, error says so."""
        settings = _settings_dict(
            {
                "llm.provider": "llamacpp",
                "llm.llamacpp_model_path": str(tmp_path),
            }
        )
        with (
            patch(f"{MODULE}.is_llm_registered", return_value=False),
            patch(
                f"{MODULE}.get_setting_from_snapshot",
                side_effect=_mock_get_setting(settings),
            ),
            patch(
                "local_deep_research.security.path_validator.PathValidator.validate_model_path",
                side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
            ),
            patch(
                "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
                return_value=tmp_path,
            ),
            patch(
                "local_deep_research.config.paths.get_models_directory",
                return_value=tmp_path,
            ),
        ):
            from local_deep_research.config.llm_config import get_llm

            with pytest.raises(ValueError, match="No .gguf files found"):
                get_llm(provider="llamacpp", settings_snapshot=settings)


class TestGetContextWindowForProviderMissing:
    """Additional coverage for _get_context_window_for_provider edge cases."""

    def test_cloud_unrestricted_false_returns_configured_size(self):
        """Cloud provider with unrestricted=False returns configured size."""

        def fake_setting(key, default, settings_snapshot=None):
            if key == "llm.context_window_unrestricted":
                return False
            if key == "llm.context_window_size":
                return 64000
            return default

        with patch(
            f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
        ):
            from local_deep_research.config.llm_config import (
                _get_context_window_for_provider,
            )

            result = _get_context_window_for_provider("anthropic")
            assert result == 64000
            assert isinstance(result, int)

    def test_local_provider_none_window_defaults_to_4096(self):
        """When local context window setting returns None, fallback to 4096."""
        with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):
            from local_deep_research.config.llm_config import (
                _get_context_window_for_provider,
            )

            result = _get_context_window_for_provider("ollama")
            assert result == 4096

    def test_cloud_restricted_none_window_defaults_to_128000(self):
        """When cloud restricted but context_window_size is None, fallback to 128000."""

        def fake_setting(key, default, settings_snapshot=None):
            if key == "llm.context_window_unrestricted":
                return False
            if key == "llm.context_window_size":
                return None
            return default

        with patch(
            f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
        ):
            from local_deep_research.config.llm_config import (
                _get_context_window_for_provider,
            )

            result = _get_context_window_for_provider("openai")
            assert result == 128000


class TestWrapLlmContextLimitInjection:
    """Tests for context_limit injection in wrap_llm_without_think_tags."""

    def test_injects_context_limit_for_local_provider(self):
        """wrap_llm sets context_limit for local provider (llamacpp)."""
        llm = MagicMock()
        research_ctx = {}

        def fake_setting(key, default=None, settings_snapshot=None):
            if key == "rate_limiting.llm_enabled":
                return False
            if key == "llm.local_context_window_size":
                return 8192
            return default

        with patch(
            f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
        ):
            from local_deep_research.config.llm_config import (
                wrap_llm_without_think_tags,
            )

            wrap_llm_without_think_tags(
                llm, provider="llamacpp", research_context=research_ctx
            )
        assert research_ctx["context_limit"] == 8192

    def test_does_not_overwrite_existing_context_limit(self):
        """If research_context already has context_limit, it is NOT overwritten."""
        llm = MagicMock()
        research_ctx = {"context_limit": 32000}

        def fake_setting(key, default=None, settings_snapshot=None):
            if key == "rate_limiting.llm_enabled":
                return False
            if key == "llm.local_context_window_size":
                return 4096
            return default

        with patch(
            f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
        ):
            from local_deep_research.config.llm_config import (
                wrap_llm_without_think_tags,
            )

            wrap_llm_without_think_tags(
                llm, provider="ollama", research_context=research_ctx
            )
        assert research_ctx["context_limit"] == 32000

    def test_model_name_attribute_used_for_token_callback(self):
        """When llm has model_name, it is used for preset_model on token callback."""
        llm = MagicMock()
        llm.model_name = "gpt-4o"
        llm.callbacks = None
        mock_counter = MagicMock()
        mock_callback = MagicMock()
        mock_counter.create_callback.return_value = mock_callback
        with (
            patch(f"{MODULE}.get_setting_from_snapshot", return_value=False),
            patch(
                "local_deep_research.metrics.TokenCounter",
                return_value=mock_counter,
            ),
        ):
            from local_deep_research.config.llm_config import (
                wrap_llm_without_think_tags,
            )

            wrap_llm_without_think_tags(llm, research_id=1, provider="openai")
        assert mock_callback.preset_model == "gpt-4o"

    def test_model_attribute_fallback_for_token_callback(self):
        """When llm has .model but NOT .model_name, .model is used."""
        llm = MagicMock(spec=["invoke", "callbacks", "model"])
        llm.model = "claude-3-haiku"
        llm.callbacks = None
        mock_counter = MagicMock()
        mock_callback = MagicMock()
        mock_counter.create_callback.return_value = mock_callback
        with (
            patch(f"{MODULE}.get_setting_from_snapshot", return_value=False),
            patch(
                "local_deep_research.metrics.TokenCounter",
                return_value=mock_counter,
            ),
        ):
            from local_deep_research.config.llm_config import (
                wrap_llm_without_think_tags,
            )

            wrap_llm_without_think_tags(
                llm, research_id=2, provider="anthropic"
            )
        assert mock_callback.preset_model == "claude-3-haiku"

    def test_cloud_unrestricted_does_not_inject_context_limit(self):
        """For cloud provider with unrestricted context, context_limit is not added."""
        llm = MagicMock()
        research_ctx = {}

        def fake_setting(key, default=None, settings_snapshot=None):
            if key == "rate_limiting.llm_enabled":
                return False
            if key == "llm.context_window_unrestricted":
                return True
            return default

        with patch(
            f"{MODULE}.get_setting_from_snapshot", side_effect=fake_setting
        ):
            from local_deep_research.config.llm_config import (
                wrap_llm_without_think_tags,
            )

            wrap_llm_without_think_tags(
                llm, provider="openai", research_context=research_ctx
            )
        assert "context_limit" not in research_ctx
