import gzip
import tempfile
import unittest
from pathlib import Path

from fgai.syslog_server import rotate_log_file


class SyslogRotationTests(unittest.TestCase):
    def test_rotation_compresses_and_prunes_archives(self):
        with tempfile.TemporaryDirectory() as temporary_directory:
            output = Path(temporary_directory) / "fg_syslog.jsonl"
            output.write_text("first log line\n", encoding="utf-8")

            archive = rotate_log_file(output, max_archives=1)

            self.assertIsNotNone(archive)
            self.assertFalse(output.exists())
            with gzip.open(archive, "rt", encoding="utf-8") as handle:
                self.assertEqual(handle.read(), "first log line\n")

            output.write_text("second log line\n", encoding="utf-8")
            rotate_log_file(output, max_archives=1)
            self.assertEqual(len(list(Path(temporary_directory).glob("fg_syslog.jsonl.*.gz"))), 1)


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