#!/usr/bin/env python3
#
# test_restore_lastmod.py - test sitemap timestamp restoration
#
# Copyright (c) 2026 by Landon Curt Noll.  All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright, this permission notice and text
# this comment, and the disclaimer below appear in all of the following:
#
#       supporting documentation
#       source copies
#       source works derived from this source
#       binaries derived from this source or from derived source
#
# LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
# EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
# chongo (Landon Curt Noll, http://www.isthe.com/chongo/index.html) /\oo/\
#
# Share and enjoy! :-)
#
"""Tests for guarded sitemap timestamp restoration."""

from pathlib import Path
import subprocess
import tempfile
import unittest


VERSION = "1.0.3 2026-12-04"
SCRIPT = Path(__file__).with_name("restore-lastmod.py").resolve()
DATE = "2024-01-02T03:04:05+00:00"
EPOCH = 1704164645


class RestoreLastmodTest(unittest.TestCase):
    """Run the public tool against a disposable Git repository."""

    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.run_git("init", "-q")
        self.run_git("config", "user.email", "test@example.invalid")
        self.run_git("config", "user.name", "Test")
        for name in ("first.html", "second.html", "missing.html", "changed.html"):
            (self.root / name).write_text(name, encoding="utf-8")
        self.run_git("add", ".")
        self.run_git("commit", "-qm", "fixture")

    def run_git(self, *args):
        subprocess.run(["git", *args], cwd=self.root, check=True, capture_output=True)

    def sitemap(self, names):
        entries = "".join(
            f"<url><loc>https://www.ioccc.org/{name}</loc><lastmod>{DATE}</lastmod></url>"
            for name in names
        )
        (self.root / "sitemap.xml").write_text(
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
            + entries + "</urlset>", encoding="utf-8",
        )

    def run_tool(self):
        return subprocess.run(
            ["python3", str(SCRIPT)], cwd=self.root, capture_output=True, text=True,
        )

    def test_missing_and_modified_files_are_reported_but_others_restored(self):
        self.sitemap(["first.html", "missing.html", "changed.html", "second.html"])
        (self.root / "missing.html").unlink()
        (self.root / "changed.html").write_text("changed", encoding="utf-8")
        old_changed = (self.root / "changed.html").stat().st_mtime_ns
        result = self.run_tool()
        self.assertNotEqual(result.returncode, 0)
        self.assertIn("missing.html", result.stderr)
        self.assertIn("changed.html", result.stderr)
        self.assertEqual((self.root / "first.html").stat().st_mtime, EPOCH)
        self.assertEqual((self.root / "second.html").stat().st_mtime, EPOCH)
        self.assertEqual((self.root / "changed.html").stat().st_mtime_ns, old_changed)

    def test_rejects_traversal_before_changing_files(self):
        self.sitemap(["first.html", "%2e%2e/outside"])
        original = (self.root / "first.html").stat().st_mtime_ns
        result = self.run_tool()
        self.assertNotEqual(result.returncode, 0)
        self.assertEqual((self.root / "first.html").stat().st_mtime_ns, original)

    def test_does_not_follow_symlink(self):
        self.sitemap(["first.html"])
        (self.root / "first.html").unlink()
        (self.root / "first.html").symlink_to("second.html")
        original = (self.root / "second.html").stat().st_mtime_ns
        result = self.run_tool()
        self.assertNotEqual(result.returncode, 0)
        self.assertEqual((self.root / "second.html").stat().st_mtime_ns, original)

    def test_index_and_worktree_changes_cannot_cancel_out(self):
        self.sitemap(["changed.html"])
        file = self.root / "changed.html"
        file.write_text("staged change", encoding="utf-8")
        self.run_git("add", "changed.html")
        file.write_text("changed.html", encoding="utf-8")
        original = file.stat().st_mtime_ns
        result = self.run_tool()
        self.assertNotEqual(result.returncode, 0)
        self.assertEqual(file.stat().st_mtime_ns, original)


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