from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from docx import Document

from epione_templates import load_template_data
from epione_templates.docx_forms import write_docx_outputs


class DocxFormTests(unittest.TestCase):
    def test_writes_procedure_docx_and_condition_folders(self) -> None:
        data = load_template_data()
        procedure_count = sum(1 for form in data["forms"] if form.get("form_type") == "Procedure")

        with tempfile.TemporaryDirectory() as temp_dir:
            outputs = write_docx_outputs(data, Path(temp_dir))
            procedure_files = list(Path(outputs["procedure_docx"]).glob("*.docx"))
            condition_folders = [path for path in Path(outputs["condition_folders"]).iterdir() if path.is_dir()]

        self.assertEqual(len(procedure_files), procedure_count)
        self.assertEqual(len(condition_folders), len(data["conditions"]))

    def test_generated_docx_opens_and_contains_manual_only_field(self) -> None:
        data = load_template_data()

        with tempfile.TemporaryDirectory() as temp_dir:
            outputs = write_docx_outputs(data, Path(temp_dir))
            document_path = Path(outputs["procedure_docx"]) / "knee_ia_steroid_us.docx"
            document = Document(document_path)
            text = "\n".join(paragraph.text for paragraph in document.paragraphs)

        self.assertIn("Knee intra-articular corticosteroid injection", text)
        table_text = "\n".join(cell.text for table in document.tables for row in table.rows for cell in row.cells)
        self.assertIn("lot_expiry", table_text)
        self.assertIn("No Default", table_text)


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