"""Exercise the documented CLI, including failures that must preserve the page."""

from datetime import date
from pathlib import Path
import re
import subprocess
from tempfile import TemporaryDirectory
import unittest
from xml.etree import ElementTree as ET


TOOLS = Path(__file__).resolve().parent
DRIVER = TOOLS / "index-from-md"
ARTICLE = b"<!-- FILL IN MARKDOWN-GNEENERATED CONTENT HERE CONTENT HERE -->"
DATE = b"<!-- LAST MODIFIED DATE, YYYY-MM-DD FORMAT -->"
WRAPPER = b"<article>\r\n<header>" + ARTICLE + b"</article>\r\n<footer>" + DATE + b"</footer>"
END = "<!-- end-introduction -->"
COLLAPSE = "<!-- collapsible -->"


class ConverterTests(unittest.TestCase):
    def setUp(self):
        temp = TemporaryDirectory()
        self.addCleanup(temp.cleanup)
        self.root = Path(temp.name)
        self.wrapper = self.root / "wrapper.html"
        self.wrapper.write_bytes(WRAPPER)
        self.output = self.root / "index.html"

    def convert(self, source, *args):
        (self.root / "index.md").write_text(source, encoding="utf-8")
        return subprocess.run(
            [DRIVER, "wrapper.html", "index.md", *args], cwd=self.root,
            capture_output=True, text=True,
        )

    def test_documented_example(self):
        spec = (TOOLS / "quirks.md").read_text(encoding="utf-8")
        source = re.search(r"```markdown\n(.*?)\n```", spec, re.S)[1]
        expected = re.search(r"```html\n(.*?)\n```", spec, re.S)[1]
        result = self.convert(source)
        self.assertEqual(result.returncode, 0, result.stderr)
        page = self.output.read_bytes()
        self.assertIn(f"<footer>{date.today().isoformat()}</footer>".encode(), page)
        # Strip only indentation between elements in the documentation example.
        article = page.decode().split("</article>")[0] + "</article>"
        reference = "<article><header>" + expected + "</article>"
        self.assertEqual(re.sub(r">\s+<", "><", article), re.sub(r">\s+<", "><", reference))

    def test_nested_markers_links_and_comments(self):
        source = f"""## Introduction

{END}

{COLLAPSE}

## A [title][ref]

> {END}
> ## Quoted heading

- One
  - Two

```md
{COLLAPSE}
## Example
```

{DATE.decode()}

## Contact

[ref]: /page
"""
        result = self.convert(source, "-date", "2024-02-29")
        self.assertEqual(result.returncode, 0, result.stderr)
        page = self.output.read_bytes()
        self.assertTrue(page.startswith(b"<article>\r\n<header>"))
        self.assertTrue(page.endswith(b"</article>\r\n<footer>2024-02-29</footer>"))
        article = ET.fromstring(page.split(b"</article>")[0] + b"</article>")
        self.assertEqual([c.tag for c in article], ["header", "section", "section"])
        details = article.find("section/details")
        self.assertEqual(details.find("summary/h2/a").get("href"), "/page")
        self.assertEqual(details.findtext("blockquote/h2"), "Quoted heading")
        self.assertIsNotNone(details.find("ul/li/ul/li"))
        self.assertEqual(details.findtext("pre/code"), COLLAPSE + "\n## Example\n")
        self.assertIn(DATE, page)
        self.assertIn(END.encode(), page)

    def test_invalid_inputs_preserve_existing_output(self):
        self.output.write_bytes(b"previous page")
        for source, args, message in [
            ("Intro only", [], "missing"),
            (f"{END}\n\n{END}", [], "index.md:3: duplicate"),
            (COLLAPSE, [], "index.md:1:"),
            (f"{END}\n{COLLAPSE}", [], "index.md:2:"),
            (f"{END}\n{COLLAPSE}\n### Subheading", [], "top-level ##"),
            (f"{END}\n{COLLAPSE}\n\n[ref]: /x\n\n## Heading", [], "top-level ##"),
            (END, ["-date", "2026-02-29"], "YYYY-MM-DD"),
            (END, ["-date", "20261127"], "YYYY-MM-DD"),
        ]:
            with self.subTest(source=source, args=args):
                result = self.convert(source, *args)
                self.assertNotEqual(result.returncode, 0)
                self.assertIn(message, result.stderr)
                self.assertEqual(self.output.read_bytes(), b"previous page")
        for slot in [ARTICLE, DATE]:
            for replacement, message in [(b"", "missing"), (slot * 2, "duplicate")]:
                with self.subTest(slot=slot, message=message):
                    self.wrapper.write_bytes(WRAPPER.replace(slot, replacement))
                    result = self.convert(END)
                    self.assertNotEqual(result.returncode, 0)
                    self.assertIn(message, result.stderr)
                    self.assertEqual(self.output.read_bytes(), b"previous page")

    def test_determinism_and_date_override(self):
        for stamp in ["2026-11-26", "2026-11-27", "2026-11-27"]:
            result = self.convert(END, "-o", "preview.html", "-date", stamp)
            self.assertEqual(result.returncode, 0, result.stderr)
            expected = WRAPPER.replace(ARTICLE, b"</header>\n").replace(DATE, stamp.encode())
            self.assertEqual((self.root / "preview.html").read_bytes(), expected)
            self.assertFalse(self.output.exists())


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