#!/usr/bin/env python3
"""Run with: python3 -m unittest discover -s build/test -p 'test_html_text_typography.py'."""

import importlib.util
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest


SCRIPT = Path(__file__).resolve().parents[1] / "html_text_typography.py"
SPEC = importlib.util.spec_from_file_location("html_text_typography", SCRIPT)
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)
transform = MODULE.transform


class TextTypographyTest(unittest.TestCase):
    def test_separator_keeps_attributes_and_wraps_visible_text(self):
        # Murakami image alts and attention-overview title tooltips triggered Tidy.
        source = '<p><img alt="Caption • Figure 1a.6" src="x"><a title="Attention • Transformer">A • B</a></p>'
        expected = source.replace('>A • B<', '>A <span class="separator-inline">•</span> B<')
        self.assertEqual(transform(source, "separator"), expected)

    def test_fraction_keeps_attributes_and_respects_word_boundaries(self):
        source = '<p title="1⁄2">1⁄2 1234⁄5678 12345⁄6 1⁄23456 x1⁄2 1⁄2x</p>'
        expected = '<p title="1⁄2"><span class="fraction">1⁄2</span> <span class="fraction">1234⁄5678</span> 12345⁄6 1⁄23456 x1⁄2 1⁄2x</p>'
        self.assertEqual(transform(source, "fraction"), expected)

    def test_preserves_raw_text_comments_code_and_existing_wrappers(self):
        protected = '\n'.join(f'<{tag}>A • B 1⁄2</{tag}>' for tag in ("script", "style", "title", "textarea", "pre", "code"))
        protected += '\n<!-- A • B 1⁄2 --><span class="fraction">1⁄2</span><span class="separator-inline"> • </span><span class="math inline">A • B 1⁄2</span>'
        for mode in ("fraction", "separator"):
            self.assertEqual(transform(protected, mode), protected)

    def test_preserves_literal_entities_and_multiline_tags(self):
        source = '<!DOCTYPE html>\r\n<p\r\n title=\'A • B 1⁄2 &amp; "quote"\'>&#8226; &bull; &amp; A • B\r\n1⁄2</p>'
        expected = source.replace("&amp; A • B", '&amp; A <span class="separator-inline">•</span> B')
        expected = expected.replace('\r\n1⁄2</p>', '\r\n<span class="fraction">1⁄2</span></p>')
        self.assertEqual(transform(transform(source, "fraction"), "separator"), expected)

    def test_nested_and_void_elements_do_not_disable_later_text(self):
        source = '<pre><code>A • B</code></pre><p><img alt="C • D"/><br>A • B</p>'
        self.assertEqual(transform(source, "separator"), source.replace('<br>A • B', '<br>A <span class="separator-inline">•</span> B'))

    def test_idempotent_without_skipping_rest_of_line(self):
        source = '<p><span class="fraction">1⁄2</span> 3⁄4 A • B</p>'
        once = transform(transform(source, "fraction"), "separator")
        twice = transform(transform(once, "fraction"), "separator")
        self.assertEqual(twice, once)
        self.assertIn('<span class="fraction">3⁄4</span>', once)

    def test_cli_processes_multiple_files_without_changing_newlines(self):
        with tempfile.TemporaryDirectory() as directory:
            paths = [Path(directory) / f"{i}.html" for i in range(2)]
            for path in paths:
                path.write_bytes(b'<p title="raw">A \xe2\x80\xa2 B</p>\r\n')
            subprocess.run([sys.executable, str(SCRIPT), "separator", *map(str, paths)], check=True)
            for path in paths:
                self.assertEqual(path.read_bytes(), '<p title="raw">A <span class="separator-inline">•</span> B</p>\r\n'.encode())


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