import tempfile
import unittest
from pathlib import Path

from indexer.covers import (
    HEIGHT,
    WIDTH,
    choose_layout,
    cover_relpath,
    palette,
    render_png,
    render_svg,
    text_bounds,
    title_hash,
    wrap_title,
    write_cover,
)


class CoverTests(unittest.TestCase):
    def test_same_title_same_hash_and_bytes(self):
        a = "The Last Terran"
        b = "The Last Terran"
        self.assertEqual(title_hash(a), title_hash(b))
        self.assertEqual(cover_relpath(a), cover_relpath(b))
        self.assertEqual(render_svg(a), render_svg(b))
        # Leading/trailing spatie telt niet mee, zodat dezelfde titel dezelfde cover houdt.
        self.assertEqual(render_svg("  The Last Terran  "), render_svg(a))

    def test_different_titles_differ(self):
        self.assertNotEqual(render_svg("The Last Terran"), render_svg("A Short Hello"))
        self.assertNotEqual(palette("The Last Terran")["c1"], palette("A Short Hello")["c1"])

    def test_write_is_deterministic_and_stable_path(self):
        with tempfile.TemporaryDirectory() as tmp:
            dest = Path(tmp)
            rel1 = write_cover(dest, "The Last Terran")
            data1 = (dest / rel1).read_bytes()
            rel2 = write_cover(dest, "The Last Terran")
            data2 = (dest / rel2).read_bytes()
            self.assertEqual(rel1, rel2)
            self.assertEqual(data1, data2)
            self.assertTrue(rel1.startswith("covers/"))
            self.assertTrue(rel1.endswith(".png") or rel1.endswith(".svg"))
            data = (dest / rel1).read_bytes()
            if rel1.endswith(".png"):
                self.assertTrue(data.startswith(b"\x89PNG"))
            else:
                self.assertTrue(data.startswith(b"<svg"))

    def test_svg_is_well_formed_and_sized(self):
        svg = render_svg("The Last Terran")
        self.assertIn('xmlns="http://www.w3.org/2000/svg"', svg)
        self.assertIn(f'width="{WIDTH}"', svg)
        self.assertIn(f'height="{HEIGHT}"', svg)
        self.assertIn("The Last Terran", svg)
        self.assertIn("<linearGradient", svg)
        self.assertNotIn("<script", svg)

    def test_xml_special_characters_are_escaped(self):
        svg = render_svg('Cats & Dogs <OC> "Hello"')
        self.assertIn("Cats &amp; Dogs", svg)
        self.assertIn("&lt;OC&gt;", svg)
        self.assertIn("&quot;Hello&quot;", svg)
        self.assertNotIn("Cats & Dogs", svg)
        self.assertNotIn("<OC>", svg)

    def test_long_title_wraps_onto_multiple_lines(self):
        title = (
            "Wearing Power Armor to a Magic School After the Council Meeting "
            "and the Unexpected Arrival of the Third Diplomatic Envoy"
        )
        font_size, lines = choose_layout(title)
        self.assertGreaterEqual(len(lines), 3)
        limit = text_bounds(title)["line_max_chars"]
        for line in lines:
            # Ellipsis mag één teken over de schatting gaan; verder niet.
            self.assertLessEqual(len(line.rstrip("…")), limit)
        bounds = text_bounds(title)
        self.assertLessEqual(bounds["last_bottom"], HEIGHT - 8)
        self.assertGreaterEqual(bounds["band_top"], 0)
        svg = render_svg(title)
        self.assertGreaterEqual(svg.count("<tspan"), 3)
        # De titel staat als geheel in aria-label, maar niet als één tekstregel.
        self.assertNotIn(f">{title}<", svg)

    def test_very_long_word_breaks_and_ellipsis(self):
        title = "Supercalifragilisticexpialidocious" * 6
        lines = wrap_title(title, max_chars=12, max_lines=4)
        self.assertEqual(len(lines), 4)
        self.assertTrue(lines[-1].endswith("…"))
        for line in lines[:-1]:
            self.assertLessEqual(len(line), 12)
        bounds = text_bounds(title)
        self.assertLessEqual(bounds["last_bottom"], HEIGHT - 8)

    def test_png_is_deterministic_and_sized(self):
        a = render_png("The Last Terran")
        b = render_png("The Last Terran")
        self.assertEqual(a, b)
        self.assertTrue(a.startswith(b"\x89PNG"))
        from io import BytesIO
        from PIL import Image
        img = Image.open(BytesIO(a))
        self.assertEqual(img.size, (WIDTH, HEIGHT))
        self.assertLess(len(a), 80_000)

    def test_png_long_title_stays_inside_the_frame(self):
        title = (
            "Wearing Power Armor to a Magic School After the Council Meeting "
            "and the Unexpected Arrival of the Third Diplomatic Envoy"
        )
        bounds = text_bounds(title)
        self.assertGreaterEqual(len(bounds["lines"]), 3)
        self.assertLessEqual(bounds["last_bottom"], HEIGHT - 8)
        png = render_png(title)
        self.assertTrue(png.startswith(b"\x89PNG"))

    def test_empty_title_uses_untitled(self):
        self.assertEqual(wrap_title("", 16, 4), ["Untitled"])
        self.assertIn("Untitled", render_svg("   "))
        self.assertEqual(title_hash(""), title_hash("Untitled"))


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