"""
Management command to export departments, locations, sections, and subsections to CSV files.

Usage:
    python manage.py export_org_csv --output-dir ./exports
"""
import csv
import os
from django.core.management.base import BaseCommand
from apps.organizations.models import Department, LegacyLocation, LegacyMainSection, LegacySubSection


class Command(BaseCommand):
    help = 'Export departments, locations, main sections, and subsections to CSV files'

    def add_arguments(self, parser):
        parser.add_argument(
            '--output-dir',
            type=str,
            default='./exports',
            help='Directory to export CSV files to'
        )

    def handle(self, *args, **options):
        output_dir = options['output_dir']
        os.makedirs(output_dir, exist_ok=True)

        # Export departments
        departments_file = os.path.join(output_dir, 'departments.csv')
        with open(departments_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['ID', 'Hospital', 'Code', 'Name (EN)', 'Name (AR)', 'Status'])
            for dept in Department.objects.all().select_related('hospital'):
                writer.writerow([
                    str(dept.id),
                    dept.hospital.name if dept.hospital else '',
                    dept.code or '',
                    dept.name_en or dept.name or '',
                    dept.name_ar or '',
                    dept.status
                ])
        self.stdout.write(self.style.SUCCESS(f'Exported {Department.objects.count()} departments to {departments_file}'))

        # Export locations
        locations_file = os.path.join(output_dir, 'locations.csv')
        with open(locations_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['ID', 'Name (EN)', 'Name (AR)'])
            for loc in LegacyLocation.objects.all():
                writer.writerow([
                    str(loc.id),
                    loc.name_en or '',
                    loc.name_ar or ''
                ])
        self.stdout.write(self.style.SUCCESS(f'Exported {LegacyLocation.objects.count()} locations to {locations_file}'))

        # Export main sections
        main_sections_file = os.path.join(output_dir, 'main_sections.csv')
        with open(main_sections_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['ID', 'Name (EN)', 'Name (AR)'])
            for section in LegacyMainSection.objects.all():
                writer.writerow([
                    str(section.id),
                    section.name_en or '',
                    section.name_ar or ''
                ])
        self.stdout.write(self.style.SUCCESS(f'Exported {LegacyMainSection.objects.count()} main sections to {main_sections_file}'))

        # Export subsections
        subsections_file = os.path.join(output_dir, 'subsections.csv')
        with open(subsections_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['Internal ID', 'Name (EN)', 'Name (AR)', 'Location (EN)', 'Location (AR)', 'Main Section (EN)', 'Main Section (AR)'])
            for sub in LegacySubSection.objects.all().select_related('location', 'main_section'):
                writer.writerow([
                    str(sub.internal_id),
                    sub.name_en or '',
                    sub.name_ar or '',
                    sub.location.name_en if sub.location else '',
                    sub.location.name_ar if sub.location else '',
                    sub.main_section.name_en if sub.main_section else '',
                    sub.main_section.name_ar if sub.main_section else ''
                ])
        self.stdout.write(self.style.SUCCESS(f'Exported {LegacySubSection.objects.count()} subsections to {subsections_file}'))

        self.stdout.write(self.style.SUCCESS(f'\nAll exports completed in: {output_dir}'))
