"""Tests for scripts/faithful_restyle.py — verbatim faculty-content fidelity."""

import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))

import faithful_restyle as fr  # noqa: E402

NESTED = """
<h2>Instructions</h2>
<ul>
  <li>First step is to read the brief carefully</li>
  <li>Second step has a sub-list
    <ul>
      <li>Nested item alpha</li>
      <li>Nested item beta</li>
    </ul>
  </li>
</ul>
<h2>Next Section</h2>
<p>Should not be included.</p>
"""

WITH_LINK = """
<h3>Resources</h3>
<p>See the <a href="https://example.com/doc?verifier=ABC123">official doc</a> for details.</p>
"""


class ExtractTest(unittest.TestCase):
    def test_nested_ul_li_text_preserved(self):
        section = fr.extract_section(NESTED, "Instructions")
        for txt in ("First step is to read the brief carefully",
                    "Second step has a sub-list",
                    "Nested item alpha", "Nested item beta"):
            self.assertIn(txt, section)
        # Stops before the next same-level heading
        self.assertNotIn("Should not be included", section)

    def test_restyle_preserves_nested_text_verbatim(self):
        section = fr.extract_section(NESTED, "Instructions")
        out = fr.restyle(section)
        self.assertTrue(fr.verify_verbatim(section, out))


class TokenPreservationTest(unittest.TestCase):
    def test_href_and_verifier_token_preserved(self):
        section = fr.extract_section(WITH_LINK, "Resources")
        out = fr.restyle(section)
        self.assertIn('href="https://example.com/doc?verifier=ABC123"', out)
        self.assertIn("verifier=ABC123", out)


class DriftTest(unittest.TestCase):
    def test_verify_verbatim_detects_drift(self):
        source = "<p>The deadline is Friday at noon.</p>"
        altered = "<p>The deadline is Monday at noon.</p>"
        self.assertFalse(fr.verify_verbatim(source, altered))

    def test_verify_verbatim_true_on_restyle(self):
        source = "<p>Unchanged text here.</p>"
        styled = fr.restyle(source)
        self.assertTrue(fr.verify_verbatim(source, styled))


class RestyleInjectsStyleTest(unittest.TestCase):
    def test_structural_tags_get_style_attrs(self):
        frag = "<ul><li>one</li></ul><p>para</p><a href='#'>link</a>"
        out = fr.restyle(frag)
        soup = fr.BeautifulSoup(out, "html.parser")
        for tag_name in ("ul", "li", "p", "a"):
            tag = soup.find(tag_name)
            self.assertIsNotNone(tag)
            self.assertTrue(tag.get("style"), f"{tag_name} missing style attr")


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