from django.core.management.base import BaseCommand
import xml.etree.ElementTree as ET
from dokumente.models import Dokument
from dokumente.utils import build_dokument_xml_element, prettify_xml


class Command(BaseCommand):
    help = 'Export all dokumente as XML'

    def add_arguments(self, parser):
        parser.add_argument(
            '--output',
            type=str,
            help='Output file path (default: stdout)',
        )

    def handle(self, *args, **options):
        dokumente = Dokument.objects.filter(aktiv=True).prefetch_related(
            'autoren', 'pruefende', 'vorgaben__thema',
            'vorgaben__referenzen', 'vorgaben__stichworte',
            'vorgaben__checklistenfragen', 'vorgaben__vorgabekurztext_set',
            'vorgaben__vorgabelangtext_set', 'geltungsbereich_set',
            'einleitung_set', 'changelog__autoren'
        ).order_by('nummer')

        root = ET.Element('Vorgabendokumente')

        for dokument in dokumente:
            build_dokument_xml_element(dokument, root)

        xml_str = ET.tostring(root, encoding='unicode', method='xml')
        xml_output = prettify_xml(xml_str)

        if options['output']:
            with open(options['output'], 'w', encoding='utf-8') as f:
                f.write(xml_output)
            self.stdout.write(self.style.SUCCESS(f'XML exported to {options["output"]}'))
        else:
            self.stdout.write(xml_output)
