import os
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from backend.core.models import DocumentTemplate


class DocumentTemplateExportCommandTest(TestCase):
    def setUp(self):
        self.template_content = """
        - segment_type: "title"
          content: "Document Title"
        - segment_type: "subtitle"
          content: "Document Subtitle"
        """
        self.template = DocumentTemplate.objects.create(
            name="Default Template",
            content=self.template_content
        )
        self.export_file = 'exported_template.yaml'

    def tearDown(self):
        if os.path.exists(self.export_file):
            os.remove(self.export_file)

    def test_export_template(self):
        out = StringIO()
        call_command('export_template', self.export_file, stdout=out)

        self.assertIn("Template exported successfully", out.getvalue())

        with open(self.export_file, 'r') as f:
            content = f.read()
            self.assertEqual(content.strip(), self.template_content.strip())
