import json
import os
import tempfile
import unittest
from unittest.mock import patch

from weibo_image_rescue import cdn


class TestCdn(unittest.TestCase):
    def test_update_cdn_info_keeps_old_cache_when_refresh_empty(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            cdn_path = os.path.join(tmpdir, "cdn.json")
            old_ips = ["1.1.1.1", "2.2.2.2"]
            with open(cdn_path, "w", encoding="utf-8") as f:
                json.dump(old_ips, f)

            with patch("weibo_image_rescue.cdn.cdn_file", cdn_path), patch(
                "weibo_image_rescue.cdn.get_cdn", return_value=[]
            ):
                result = cdn.update_cdn_info()

            self.assertEqual(result, old_ips)
            with open(cdn_path, "r", encoding="utf-8") as f:
                self.assertEqual(json.load(f), old_ips)

    def test_update_cdn_info_overwrites_cache_when_refresh_succeeds(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            cdn_path = os.path.join(tmpdir, "cdn.json")
            with open(cdn_path, "w", encoding="utf-8") as f:
                f.write("{invalid json")

            new_ips = ["3.3.3.3"]
            with patch("weibo_image_rescue.cdn.cdn_file", cdn_path), patch(
                "weibo_image_rescue.cdn.get_cdn", return_value=new_ips
            ):
                result = cdn.update_cdn_info()

            self.assertEqual(result, new_ips)
            with open(cdn_path, "r", encoding="utf-8") as f:
                self.assertEqual(json.load(f), new_ips)

    def test_load_cdn_info_calls_update_when_file_missing(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            cdn_path = os.path.join(tmpdir, "missing.json")
            with patch("weibo_image_rescue.cdn.cdn_file", cdn_path), patch(
                "weibo_image_rescue.cdn.update_cdn_info", return_value=["9.9.9.9"]
            ) as mock_update:
                result = cdn.load_cdn_info()

            self.assertEqual(result, ["9.9.9.9"])
            mock_update.assert_called_once()

    def test_load_cdn_info_reads_existing_cache(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            cdn_path = os.path.join(tmpdir, "cdn.json")
            ips = ["8.8.8.8", "8.8.4.4"]
            with open(cdn_path, "w", encoding="utf-8") as f:
                json.dump(ips, f)

            with patch("weibo_image_rescue.cdn.cdn_file", cdn_path):
                result = cdn.load_cdn_info()

            self.assertEqual(result, ips)


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