from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from epione_templates import load_template_data
from epione_templates.static_forms import render_static_html, render_static_rtf, write_static_form_outputs


class StaticFormTests(unittest.TestCase):
    def test_html_escapes_template_content(self) -> None:
        form = {
            "form_id": "test_form",
            "title": "A < B",
            "form_type": "Procedure",
            "family": "Test",
            "fields": [
                {
                    "section": "Safety",
                    "label": "Field <unsafe>",
                    "key": "field_key",
                    "default_layer": "No Default",
                    "required": True,
                }
            ],
            "narrative_template": "Need {{field_key}} and <raw>",
        }

        output = render_static_html(form)

        self.assertIn("A &lt; B", output)
        self.assertIn("Field &lt;unsafe&gt;", output)
        self.assertIn("&lt;raw&gt;", output)
        self.assertNotIn("<raw>", output)

    def test_rtf_escapes_control_characters_and_unicode(self) -> None:
        form = {
            "form_id": "test_form",
            "title": "Brace { backslash \\ arrow →",
            "form_type": "Procedure",
            "family": "Test",
            "fields": [],
            "narrative_template": "Value {{field_key}}",
        }

        output = render_static_rtf(form)

        self.assertTrue(output.startswith("{\\rtf1"))
        self.assertIn("\\{", output)
        self.assertIn("\\\\", output)
        self.assertIn("\\u8594?", output)

    def test_writes_one_html_and_rtf_per_form(self) -> None:
        data = load_template_data()
        with tempfile.TemporaryDirectory() as temp_dir:
            output_paths = write_static_form_outputs(data, Path(temp_dir))
            html_count = len(list(Path(output_paths["form_html"]).glob("*.html")))
            rtf_count = len(list(Path(output_paths["form_rtf"]).glob("*.rtf")))

        self.assertEqual(html_count, len(data["forms"]))
        self.assertEqual(rtf_count, len(data["forms"]))


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