"""Putting document titles and dates back to what the live site shows.

The first import altered a handful of titles and, worse, invented *groups* by
bundling everything that shared an upload date and naming the bundle by
guesswork — producing "2025 AGM documents" containing the 2023, 2024 and 2025
AGM minutes. To an owner that reads as the site having its facts wrong, and it
is the first thing the client saw.
"""
import json
import shutil
import tempfile

from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management import call_command
from django.test import TestCase, override_settings

from documents.models import Collection, Document

_TMP = tempfile.mkdtemp(prefix="hartling-resync-test-")


@override_settings(PRIVATE_MEDIA_ROOT=_TMP)
class ResyncTests(TestCase):
    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(_TMP, ignore_errors=True)
        super().tearDownClass()

    def doc(self, **kw):
        kw.setdefault("file", SimpleUploadedFile("a.pdf", b"%PDF-1.4"))
        kw.setdefault("published", True)
        return Document.objects.create(**kw)

    def resync(self, rows, **kw):
        with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as fh:
            json.dump(rows, fh)
            path = fh.name
        call_command("resync_from_wordpress", file=path, **kw)

    def test_titles_and_dates_come_from_wordpress_by_id(self):
        doc = self.doc(wp_id="1247", title="Strata Corp 125 AGM Minutes",
                       published_date="2026-04-21")
        self.resync([{"ID": 1247, "post_title": "Strata Corp 125 AGM Minute",
                      "post_date": "2020-01-31", "post_status": "publish"}])
        doc.refresh_from_db()
        self.assertEqual(doc.title, "Strata Corp 125 AGM Minute")
        self.assertEqual(str(doc.published_date), "2020-01-31")

    def test_html_entities_in_wordpress_titles_are_decoded(self):
        """WordPress stores titles escaped. Copying them verbatim puts
        "&amp;" on screen — a bug this project already fixed once."""
        doc = self.doc(wp_id="9", title="placeholder")
        self.resync([{"ID": 9, "post_title": "2017 Balance Sheet &amp; Reserve Items",
                      "post_date": "2018-01-01", "post_status": "publish"}])
        doc.refresh_from_db()
        self.assertEqual(doc.title, "2017 Balance Sheet & Reserve Items")

    def test_ungroup_dissolves_the_invented_groups(self):
        group = Collection.objects.create(
            title="2025 AGM documents", slug="2025-agm", occurred_on="2026-04-21")
        a = self.doc(wp_id="1", title="2023 AGM Minutes", collection=group)
        b = self.doc(wp_id="2", title="2024 AGM minutes", collection=group)

        self.resync([{"ID": 1, "post_title": "2023 AGM Minutes",
                      "post_date": "2026-04-21", "post_status": "publish"},
                     {"ID": 2, "post_title": "2024 AGM minutes",
                      "post_date": "2026-04-21", "post_status": "publish"}],
                    ungroup=True)
        a.refresh_from_db(); b.refresh_from_db()
        self.assertIsNone(a.collection)
        self.assertIsNone(b.collection)
        self.assertEqual(Collection.objects.count(), 0)
        # ...and the documents themselves survive the group being removed.
        self.assertEqual(Document.objects.count(), 2)

    def test_documents_that_did_not_come_from_wordpress_are_left_alone(self):
        mine = self.doc(wp_id=None, title="Uploaded here", published_date="2026-01-01")
        self.resync([{"ID": 1, "post_title": "Something else",
                      "post_date": "2020-01-01", "post_status": "publish"}])
        mine.refresh_from_db()
        self.assertEqual(mine.title, "Uploaded here")

    def test_a_dry_run_changes_nothing(self):
        group = Collection.objects.create(title="G", slug="g", occurred_on="2026-04-21")
        doc = self.doc(wp_id="5", title="Original", collection=group)
        self.resync([{"ID": 5, "post_title": "Renamed",
                      "post_date": "2020-01-01", "post_status": "publish"}],
                    ungroup=True, dry_run=True)
        doc.refresh_from_db()
        self.assertEqual(doc.title, "Original")
        self.assertIsNotNone(doc.collection)
        self.assertEqual(Collection.objects.count(), 1)

    def test_draft_status_carries_across(self):
        doc = self.doc(wp_id="7", title="Draft doc", published=True)
        self.resync([{"ID": 7, "post_title": "Draft doc",
                      "post_date": "2020-01-01", "post_status": "draft"}])
        doc.refresh_from_db()
        self.assertFalse(doc.published)
