#!/usr/bin/env python3
"""Exercise sync.sh's actual Tidy options without running or sourcing the build.

Run: python3 build/test/TidyLintTest.py
Set TIDY_BIN to use a Tidy executable outside PATH.
"""

import os
from pathlib import Path
import re
import shlex
import subprocess
import tempfile
import unittest


class TidyLintTest(unittest.TestCase):
    def test_cleanup_noise_and_structural_errors(self):
        sync = (Path(__file__).resolve().parents[1] / "sync.sh").read_text()
        invocation = re.search(r'TIDY=\$\((tidy [^\n]+?) "\$HTML"', sync)
        self.assertIsNotNone(invocation, "Cannot locate sync.sh's Tidy command")
        command = shlex.split(invocation.group(1))
        command[0] = os.environ.get("TIDY_BIN", command[0])
        fixture = '''<!doctype html>
<html lang="en"><head><title>Tidy regression</title></head><body>
<span class="mjx-line" style="border-bottom: 1px solid"></span>
<span class="mjx-vsize" style="height: 1em"></span>
<span class="reader-mode-disable-when-here"></span>
<a href="#one-ℝ-to-rule-them-all">Unicode fragment</a>
<a href="https://en.wikipedia.org/wiki/Jürgen_Schmidhuber">Unicode path</a>
<a href="bad url">Illegal URI space</a>
<a id="duplicate">First</a><a id="duplicate">Second</a>
</figure><p><b>Unclosed bold</p>
</body></html>'''
        with tempfile.TemporaryDirectory() as temporary:
            path = Path(temporary) / "fixture.html"
            path.write_text(fixture)
            result = subprocess.run(command + [str(path)], capture_output=True, text=True)
        self.assertNotIn("trimming empty", result.stderr)
        self.assertNotIn("escaping malformed URI", result.stderr)
        for diagnostic in ["illegal characters found in URI", 'anchor "duplicate" already defined',
                           "discarding unexpected </figure>", "missing </b> before </p>"]:
            self.assertIn(diagnostic, result.stderr)


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