#!/usr/bin/env python3
"""Behavior checks for review-theme coding and aggregate math."""

from __future__ import annotations

import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from collect_store_reviews import (
    aggregate_rows,
    build_app_store_review_url,
    classify_text,
    write_rows,
)


class ReviewCollectorTest(unittest.TestCase):
    def test_classify_text_marks_overlapping_observable_themes(self) -> None:
        labels = classify_text(
            "The AI forgets my inventory, loops in combat, and the subscription is expensive."
        )

        self.assertEqual(
            labels,
            {
                "memory_continuity",
                "rules_combat_state",
                "repetition_output_quality",
                "price_monetization",
            },
        )

    def test_aggregate_rows_uses_literal_rating_distribution(self) -> None:
        rows = [
            {"rating": 5, "themes": {"creativity"}},
            {"rating": 1, "themes": {"bugs_stability", "creativity"}},
        ]

        aggregate = aggregate_rows(rows)

        self.assertEqual(aggregate["reviews_retrieved"], 2)
        self.assertEqual(aggregate["mean_rating"], 3.0)
        self.assertEqual(aggregate["rating_distribution"], {"1": 1, "5": 1})
        self.assertEqual(aggregate["theme_counts"]["creativity"], 2)

    def test_app_store_review_url_preserves_case_sensitive_sort_parameter(self) -> None:
        url = build_app_store_review_url({"country": "us", "id": "6475002750"}, page=1)

        self.assertEqual(
            url,
            "https://itunes.apple.com/us/rss/customerreviews/"
            "page=1/id=6475002750/sortBy=mostRecent/json",
        )

    def test_write_rows_preserves_declared_schema_for_empty_corpus(self) -> None:
        with TemporaryDirectory() as directory:
            output = Path(directory) / "empty.csv"

            write_rows(output, [], ("rating", "review_id", "updated_at", "version"))

            self.assertEqual(
                output.read_text(encoding="utf-8"),
                "rating,review_id,updated_at,version,themes\n",
            )


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