from __future__ import annotations

import unittest

from core.markdown_guard import normalize_markdown_fences

BROKEN = """前文

```markdown
```mermaid
flowchart LR
    A --> B
```
```

后文 **应正常渲染**。
"""


class MarkdownFenceGuardTests(unittest.TestCase):
    def test_repairs_equal_length_nested_fence_example(self) -> None:
        result = normalize_markdown_fences(BROKEN)

        self.assertEqual(result.repairs, 1)
        self.assertFalse(result.unclosed_fence)
        self.assertIn("````markdown\n```mermaid", result.text)
        self.assertIn("```\n````\n\n后文", result.text)

    def test_preserves_already_valid_longer_outer_fence(self) -> None:
        valid = BROKEN.replace("```markdown", "````markdown", 1).replace(
            "```\n\n后文", "````\n\n后文", 1
        )

        result = normalize_markdown_fences(valid)

        self.assertEqual(result.text, valid)
        self.assertEqual(result.repairs, 0)
        self.assertFalse(result.unclosed_fence)

    def test_preserves_arbitrary_unclosed_fence_and_reports_it(self) -> None:
        broken = "正文\n\n```python\nprint('x')\n"

        result = normalize_markdown_fences(broken)

        self.assertEqual(result.text, broken)
        self.assertEqual(result.repairs, 0)
        self.assertTrue(result.unclosed_fence)

    def test_supports_tilde_fences_and_blank_line_between_closes(self) -> None:
        broken = "~~~~md\n~~~~js\nx = 1\n~~~~\n\n~~~~\n正文\n"

        result = normalize_markdown_fences(broken)

        self.assertEqual(result.repairs, 1)
        self.assertTrue(result.text.startswith("~~~~~md\n~~~~js"))
        self.assertIn("~~~~\n\n~~~~~\n正文", result.text)


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