"""
Tests for engine.translate module.
"""

import json
from unittest.mock import MagicMock, patch

from engine.translate import (
    _translate_cached,
    detect_location_language,
    translate_headline,
)


def clear_translate_cache():
    """Clear the LRU cache between tests."""
    _translate_cached.cache_clear()


class TestDetectLocationLanguage:
    """Tests for detect_location_language function."""

    def test_returns_none_for_unknown_location(self):
        """Returns None when no location pattern matches."""
        result = detect_location_language("Breaking news about technology")
        assert result is None

    def test_detects_berlin(self):
        """Detects Berlin location."""
        result = detect_location_language("Berlin police arrest protesters")
        assert result == "de"

    def test_detects_paris(self):
        """Detects Paris location."""
        result = detect_location_language("Paris fashion week begins")
        assert result == "fr"

    def test_detects_tokyo(self):
        """Detects Tokyo location."""
        result = detect_location_language("Tokyo stocks rise")
        assert result == "ja"

    def test_detects_berlin_again(self):
        """Detects Berlin location again."""
        result = detect_location_language("Berlin marathon set to begin")
        assert result == "de"

    def test_case_insensitive(self):
        """Detection is case insensitive."""
        result = detect_location_language("BERLIN SUMMER FESTIVAL")
        assert result == "de"

    def test_returns_first_match(self):
        """Returns first matching pattern."""
        result = detect_location_language("Berlin in Paris for the event")
        assert result == "de"


class TestTranslateHeadline:
    """Tests for translate_headline function."""

    def test_returns_translated_text(self):
        """Returns translated text from cache."""
        clear_translate_cache()
        with patch("engine.translate.translate_headline") as mock_fn:
            mock_fn.return_value = "Translated title"
            from engine.translate import translate_headline as th

            result = th("Original title", "de")
            assert result == "Translated title"

    def test_uses_cached_result(self):
        """Translation uses LRU cache."""
        clear_translate_cache()
        result1 = translate_headline("Test unique", "es")
        result2 = translate_headline("Test unique", "es")
        assert result1 == result2


class TestTranslateCached:
    """Tests for _translate_cached function."""

    def test_translation_network_error(self):
        """Network error returns original text."""
        clear_translate_cache()
        with patch("engine.translate.urllib.request.urlopen") as mock_urlopen:
            mock_urlopen.side_effect = Exception("Network error")

            result = _translate_cached("Hello world", "de")

            assert result == "Hello world"

    def test_translation_invalid_json(self):
        """Invalid JSON returns original text."""
        clear_translate_cache()
        with patch("engine.translate.urllib.request.urlopen") as mock_urlopen:
            mock_response = MagicMock()
            mock_response.read.return_value = b"invalid json"
            mock_urlopen.return_value = mock_response

            result = _translate_cached("Hello", "de")

            assert result == "Hello"

    def test_translation_empty_response(self):
        """Empty translation response returns original text."""
        clear_translate_cache()
        with patch("engine.translate.urllib.request.urlopen") as mock_urlopen:
            mock_response = MagicMock()
            mock_response.read.return_value = json.dumps([[[""], None, "de"], None])
            mock_urlopen.return_value = mock_response

            result = _translate_cached("Hello", "de")

            assert result == "Hello"
