from unittest.mock import MagicMock

import requests

from GramAddict.core.llm_provider import query_telepathic_llm


class TestLLMProvider:
    def test_vlm_timeout_aborts_fast_connections(self, monkeypatch):
        """
        OpenRouter/Cloud connections must timeout around ~45s.
        If a timeout exception is raised by requests, query_telepathic_llm should gracefully catch it
        and return empty "{}" JSON.
        """

        def mock_post(*args, **kwargs):
            timeout = kwargs.get("timeout")
            assert timeout == 45, "Expected 45s strict timeout for openrouter"
            raise requests.exceptions.ReadTimeout("Mocked read timeout")

        monkeypatch.setattr(requests, "post", mock_post)

        # Test Cloud URL
        result = query_telepathic_llm(
            model="openrouter/qwen3.5:latest",
            url="https://openrouter.ai/api/v1/chat/completions",
            system_prompt="sys",
            user_prompt="user",
            use_local_edge=False,
        )

        assert result == "{}"

    def test_vlm_timeout_allows_local_processing(self, monkeypatch):
        """
        Localhost (Ollama) connections must have a significantly higher timeout (180s)
        so cold starts loading into VRAM don't drop.
        """

        def mock_post(*args, **kwargs):
            kwargs.get("url") or args[0]
            timeout = kwargs.get("timeout")
            assert timeout == 180, f"Expected 180s extended timeout for localhost, got {timeout}"

            mock_resp = MagicMock()
            mock_resp.status_code = 200
            # For ollama/vllm mimic structure
            mock_resp.json.return_value = {"response": '{"clicked": "true"}'}
            return mock_resp

        monkeypatch.setattr(requests, "post", mock_post)

        # Test Local URL
        result = query_telepathic_llm(
            model="qwen3.5:latest",
            url="http://localhost:11434/api/generate",
            system_prompt="sys",
            user_prompt="user",
            use_local_edge=False,
        )

        assert result == '{"clicked": "true"}'

    def test_local_edge_override_applies_timeout(self, monkeypatch):
        """
        If use_local_edge=True is set, it overrides the URL to localhost and MUST apply 180s.
        """

        def mock_post(*args, **kwargs):
            timeout = kwargs.get("timeout")
            assert timeout == 180, "Expected 180s extended timeout when forced to local edge"
            mock_resp = MagicMock()
            mock_resp.status_code = 200
            mock_resp.json.return_value = {"response": '{"edge": "true"}'}
            return mock_resp

        monkeypatch.setattr(requests, "post", mock_post)

        result = query_telepathic_llm(
            model="openrouter",
            url="https://openrouter...",
            system_prompt="sys",
            user_prompt="user",
            use_local_edge=True,  # Force local
        )

        assert result == '{"edge": "true"}'
