#!/usr/bin/env python3
"""Tests for set_app_store_whats_new.py's fill-empty backstop mode."""

from __future__ import annotations

import sys
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent))

import set_app_store_whats_new as sw  # noqa: E402


def _loc(loc_id, locale, whats_new=None):
    attrs = {"locale": locale}
    if whats_new is not None:
        attrs["whatsNew"] = whats_new
    return {"id": loc_id, "attributes": attrs}


class UpdateAllLocalizationsTests(unittest.TestCase):
    def _run(self, entries, only_if_empty):
        patched = []

        def fake_patch(token, loc_id, whats_new):
            patched.append(loc_id)
            return True

        with mock.patch.object(sw, "get_json", return_value={"data": entries}), \
                mock.patch.object(sw, "_patch_localization", side_effect=fake_patch):
            count = sw._update_all_localizations(
                "tok", "v1", "1.0.1", "DEFAULT", "en-US",
                only_if_empty=only_if_empty)
        return count, patched

    def test_force_mode_patches_every_locale(self):
        entries = [_loc("a", "en-US", "existing"), _loc("b", "ru", ""),
                   _loc("c", "de", None)]
        count, patched = self._run(entries, only_if_empty=False)
        self.assertEqual(count, 3)
        self.assertEqual(set(patched), {"a", "b", "c"})

    def test_backstop_fills_only_empty_locales(self):
        entries = [_loc("a", "en-US", "AI generated notes"),
                   _loc("b", "ru", ""),      # empty -> fill
                   _loc("c", "de", "   "),    # blank whitespace -> fill
                   _loc("d", "fr", None)]     # missing -> fill
        count, patched = self._run(entries, only_if_empty=True)
        self.assertEqual(count, 3)
        self.assertEqual(set(patched), {"b", "c", "d"})
        self.assertNotIn("a", patched)  # AI content preserved

    def test_backstop_noop_when_all_present(self):
        entries = [_loc("a", "en-US", "notes"), _loc("b", "ru", "notes")]
        count, patched = self._run(entries, only_if_empty=True)
        self.assertEqual(count, 0)
        self.assertEqual(patched, [])

    def test_seeds_when_no_localizations(self):
        with mock.patch.object(sw, "get_json", return_value={"data": []}), \
                mock.patch.object(sw, "_create_localization", return_value="new1") as cre:
            count = sw._update_all_localizations(
                "tok", "v1", "1.0.1", "DEFAULT", "en-US", only_if_empty=True)
        self.assertEqual(count, 1)
        cre.assert_called_once()


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