import csv
import os

from django.core.management.base import BaseCommand

from apps.organizations.models import Department, LegacySubSection


class Command(BaseCommand):
    help = "Export departments and complaint 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)

        self._export_departments(output_dir)
        self._export_subsections(output_dir)

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

    def _export_departments(self, output_dir):
        filepath = os.path.join(output_dir, "departments.csv")
        with open(filepath, "w", newline="", encoding="utf-8-sig") as f:
            writer = csv.writer(f)
            writer.writerow([
                "ID",
                "Hospital Name",
                "Hospital Code",
                "Code",
                "Name",
                "Name (EN)",
                "Name (AR)",
                "Category",
                "Status",
                "Parent Department",
                "Manager",
                "Phone",
                "Email",
                "Location",
                "Created At",
            ])
            qs = Department.objects.select_related(
                "hospital", "parent", "manager"
            ).order_by("hospital__name", "name")
            for dept in qs:
                writer.writerow([
                    str(dept.id),
                    dept.hospital.name if dept.hospital else "",
                    getattr(dept.hospital, "code", "") if dept.hospital else "",
                    dept.code or "",
                    dept.name or "",
                    dept.name_en or "",
                    dept.name_ar or "",
                    dept.get_category_display() if dept.category else "",
                    dept.get_status_display() if dept.status else "",
                    dept.parent.name if dept.parent else "",
                    dept.manager.get_full_name() if dept.manager else "",
                    dept.phone or "",
                    dept.email or "",
                    dept.location or "",
                    dept.created.strftime("%Y-%m-%d %H:%M") if hasattr(dept, "created") and dept.created else "",
                ])
        count = qs.count()
        self.stdout.write(
            self.style.SUCCESS(
                f"Exported {count} departments to {filepath}"
            )
        )

    def _export_subsections(self, output_dir):
        filepath = os.path.join(output_dir, "subsections.csv")
        with open(filepath, "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)",
            ])
            qs = LegacySubSection.objects.select_related(
                "location", "main_section"
            ).order_by("location__name_en", "main_section__name_en", "name_en")
            for sub in qs:
                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 "",
                ])
        count = qs.count()
        self.stdout.write(
            self.style.SUCCESS(
                f"Exported {count} subsections to {filepath}"
            )
        )
