"""Words-only compatibility. Synthetic data only; this module never generates a directory."""
import datetime as dt
from pathlib import Path
import sys
import unittest

from jinja2 import Environment, FileSystemLoader, select_autoescape

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import rating
import svg


TODAY = dt.date(2026, 11, 17)
OLD = "2026-01-01"


class WordsOnlyGeneratorCompatibility(unittest.TestCase):
    def test_mirror_counts_only_starred_reviews(self):
        rows = [{"stars": {"org": 5}, "text": "", "account_created": OLD},
                {"stars": {"org": 3}, "text": "", "account_created": OLD},
                {"stars": {}, "text": "Synthetic written-only review.", "account_created": OLD}]
        result = rating.summarise(rows, TODAY)
        self.assertEqual((result["count"], result["written"], result["shown"]), (2, 1, False))

    def test_server_summary_accepts_more_written_than_starred(self):
        result = rating.normalise({"shown": False, "count": 0, "written": 1}, 1, "synthetic-school")
        self.assertEqual((result["count"], result["written"]), (0, 1))

    def test_review_score_renders_null_without_zero_rating(self):
        env = Environment(loader=FileSystemLoader(Path(__file__).resolve().parents[1] / "template"),
                          autoescape=select_autoescape(["html", "j2"]))
        env.globals["svg"] = svg
        result = env.get_template("parts/reviews.j2").render(
            rating_shown=False, rating_kind="empty", rating_avg=0,
            ato={"rating": {"count": 0}, "bases": []}, written_count=1, rated_hi=None,
            star_bars=[], cat_rows=[], verified=False, paid=False, more=0,
            top=[{"id": "synthetic-review", "author": {"anonymous": False, "name": "Synthetic Pilot",
                  "badges": [], "licences": []}, "when_label": "17 Nov 2026", "stars": None,
                  "edited": False, "title": None, "text": "Synthetic written-only review.", "official_replies": []}])
        self.assertNotIn("0.0 out of 5 stars", result)
        self.assertNotIn(">0.0</b>", result)
        self.assertIn('aria-label="Rating not shown yet"', result)

    def test_mirror_threshold_categories_and_bars_ignore_words_only(self):
        rows = [{"stars": {"org": n}, "text": "", "account_created": OLD} for n in (3, 4, 5)]
        scored = rating.summarise(rows, TODAY)
        extras = [{"stars": s, "text": "Written without scores", "account_created": OLD}
                  for s in (None, {}, {"org": None, "flt": None}, {})]
        extras.append({"text": "Missing scores are written-only too", "account_created": OLD})
        extras += [{"stars": None, "text": "", "status": "deleted", "account_created": OLD},
                   {"stars": {"org": 1}, "text": "Held text", "status": "spam_held", "account_created": OLD}]
        for mode in ("review_overalls", "every_star"):
            result = rating.summarise(rows + extras, TODAY, mode=mode)
            self.assertEqual(result["written"], 5)
            for field in ("shown", "count", "score", "gold", "bars", "categories", "rated_hi"):
                self.assertEqual(result[field], scored[field], field)
            self.assertEqual(rating.normalise(result, 0)["written"], 5)
        rows[2]["account_created"] = "2026-11-16"
        self.assertFalse(rating.summarise(rows + extras, TODAY)["shown"], "old words-only authors cannot satisfy the aged-score threshold")

    def test_written_count_remains_a_nonnegative_integer(self):
        for written in (-1, 0.5, True, "2", [], {}):
            with self.subTest(written=written), self.assertRaises(ValueError):
                rating.normalise({"shown": False, "count": 0, "written": written}, 0)


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