"""
Arabic sub-department name -> Department code mapping.

Used by complaint import scripts to set the `department` FK based on the
Arabic القسم الفرعي (sub-department) column in the historical Excel files.

All codes target HH-N (Al Nuzha) since historical data is from that hospital.
"""

import re


def normalize_arabic(text: str) -> str:
    if not text:
        return ""
    text = str(text).strip()
    text = text.replace("\u0623", "\u0627")  # أ → ا
    text = text.replace("\u0625", "\u0627")  # إ → ا
    text = text.replace("\u0622", "\u0627")  # آ → ا
    text = text.replace("\u0649", "\u064a")  # ى → ي
    text = re.sub(r"\s+", " ", text)
    text = text.strip()
    return text


# Canonical Arabic name → department code
# All codes are HH-N (Nuzha) department codes
ARABIC_TO_DEPT_CODE = {
    # Pharmacy
    "قسم الصيدلية": "hh_n_pharmacy_department",
    "صيدلية الطوارئ": "hh_n_pharmacy_department",
    "قسم الصيدلية - السويدي": "hh_n_pharmacy_department",
    # Laboratory
    "قسم المختبر": "hh_n_laboratory_department",
    "استقبال المختبر": "hh_n_laboratory_department",
    "بنك الدم": "hh_n_laboratory_department",
    # Medical Approvals
    "قسم الموافقات الطبية": "hh_n_medical_approvals_department",
    "الموافقات الطبية": "hh_n_medical_approvals_department",
    # Medical Records
    "قسم التقارير الطبية": "hh_n_medical_records_department",
    # Financial
    "قسم المالية": "hh_n_financial_collection___claims_department",
    # Dental
    "عيادات الأسنان": "hh_n_dental_department",
    # Ophthalmology
    "عيادات العيون": "hh_n_ophthalmology_department",
    "عيادات جراحة العيون": "hh_n_ophthalmology_department",
    "فني فحص النظر": "hh_n_ophthalmology_department",
    # Dermatology
    "عيادات الجلدية": "hh_n_dermatology_department",
    "عيادات الجلديه": "hh_n_dermatology_department",
    # OB/GYN
    "عيادات النساء والولادة": "hh_n_obstetrics___gynecology_department",
    "تنويم النساء والولادة": "hh_n_obstetrics___gynecology_department",
    "تنويم النساء والولاده": "hh_n_obstetrics___gynecology_department",
    "قسم عمليات الولادة": "hh_n_obstetrics___gynecology_department",
    "تمريض تنويم النساء والولادة": "hh_n_obstetrics___gynecology_department",
    "تمريض قسم عمليات الولادة": "hh_n_nursing_department",
    # Pediatric
    "عيادات الأطفال": "hh_n_pediatric_department",
    "تنويم الأطفال": "hh_n_pediatric_department",
    "تنويم الاطفال": "hh_n_pediatric_department",
    "تمريض تنويم الأطفال": "hh_n_pediatric_department",
    "تمريض تنويم الاطفال": "hh_n_pediatric_department",
    "عيادات الأنف والأذن والحنجرة (أطفال)": "hh_n_pediatric_department",
    "عيادات الصدرية (أطفال)": "hh_n_pediatric_department",
    "عيادات الجهاز الهمضي والمناظير (أطفال)": "hh_n_pediatric_department",
    "عيادات جراحة عظام (أطفال)": "hh_n_pediatric_department",
    "عيادات جراحة المسالك البولية (أطفال)": "hh_n_pediatric_department",
    "عيادات قلب (أطفال)": "hh_n_pediatric_department",
    "عيادات المخ والأعصاب (أطفال)": "hh_n_pediatric_department",
    "عيادات الجراحة العامة (أطفال)": "hh_n_pediatric_department",
    "تمريض الحضانة": "hh_n_pediatric_department",
    "وحدة العناية المركزة لحديثي الولادة": "hh_n_pediatric_department",
    "وحدة العناية المركزة للأطفال": "hh_n_pediatric_department",
    "قسم الحضانة": "hh_n_pediatric_department",
    "تمريض وحدة العناية المركزة - أطفال": "hh_n_pediatric_department",
    "تمريض وحدة العناية لحديثي الولادة": "hh_n_pediatric_department",
    # Surgery
    "عيادات جراحة العظام": "hh_n_surgery_department",
    "عيادات جراحه العظام": "hh_n_surgery_department",
    "قسم جراحة العظام": "hh_n_surgery_department",
    "عيادات الجراحة العامة": "hh_n_surgery_department",
    "قسم الجراحة العامة": "hh_n_surgery_department",
    "قسم جراحة المسالك البولية": "hh_n_surgery_department",
    "عيادات جراحة المسالك البولية": "hh_n_surgery_department",
    "عيادات جراحة الأنف وأذن وحنجرة": "hh_n_surgery_department",
    "جراحه الانف واذن وحنجره": "hh_n_surgery_department",
    "عيادات جراحة الأوعية الدموية": "hh_n_surgery_department",
    "عيادات جراحة المخ والأعصاب": "hh_n_surgery_department",
    "عيادات جراحة القفص الصدري": "hh_n_surgery_department",
    "عيادات جراحة العمود الفقري": "hh_n_surgery_department",
    "عيادات جراحة التجميلية": "hh_n_surgery_department",
    "عيادات الجراحة التجميلية": "hh_n_surgery_department",
    "عيادات جراحة سمنة": "hh_n_surgery_department",
    "قسم جراحة السمنة": "hh_n_surgery_department",
    "عيادات جراحة الختان": "hh_n_surgery_department",
    "عيادات جراحة الأورام و الغدد الصماء": "hh_n_surgery_department",
    "تمريض تنويم الجراحة العامة": "hh_n_surgery_department",
    "تنويم الجراحة العامة": "hh_n_surgery_department",
    "تنويم الباطنية": "hh_n_internal_medicine_department",
    # Internal Medicine
    "عيادات الباطنية": "hh_n_internal_medicine_department",
    "عيادات القلب": "hh_n_internal_medicine_department",
    "عيادات الجهاز الهضمي والمناظير": "hh_n_internal_medicine_department",
    "قسم الجهاز الهمضي و الكبد والمناظير": "hh_n_internal_medicine_department",
    "قسم الجهاز الهضمي والكبد والمناظير": "hh_n_internal_medicine_department",
    "عيادات الصدرية": "hh_n_internal_medicine_department",
    "عيادات الصدريه": "hh_n_internal_medicine_department",
    "قسم الصدرية": "hh_n_internal_medicine_department",
    "عيادات الغدد الصماء": "hh_n_internal_medicine_department",
    "عيادات المخ والأعصاب": "hh_n_internal_medicine_department",
    "عيادات الكلى": "hh_n_internal_medicine_department",
    "عيادات التخدير": "hh_n_anesthesia_department",
    "عيادات الطب النفسي": "hh_n_internal_medicine_department",
    "وحدة المناظير": "hh_n_internal_medicine_department",
    "تمريض تنويم الباطنية": "hh_n_internal_medicine_department",
    "قسم العلاج الطبيعي": "hh_n_medical_ancillary_services_department",
    "استقبال العلاج الطبيعي": "hh_n_medical_ancillary_services_department",
    "العلاج الطبيعي": "hh_n_medical_ancillary_services_department",
    # Anesthesia
    "قسم التخدير": "hh_n_anesthesia_department",
    "تمريض التخدير": "hh_n_anesthesia_department",
    # Emergency
    "أطباء الطوارئ": "hh_n_emergency_medicine_department",
    "استقبال الطوارئ": "hh_n_emergency_administrative_department",
    "استقبال الطواريء": "hh_n_emergency_administrative_department",
    "استقبال العيادات الخارجية": "hh_n_outpatient_department",
    # Critical Care
    "وحدة العناية المركزة": "hh_n_critical_care_department",
    "وحدة العناية المتوسطة": "hh_n_critical_care_department",
    "تمريض وحدة العناية المركزة": "hh_n_critical_care_department",
    "تمريض وحدة العناية المتوسطة": "hh_n_critical_care_department",
    "تمريض وحدة طويلي الإقامة": "hh_n_critical_care_department",
    "وحدة مرضى طويلي الإقامة": "hh_n_critical_care_department",
    # Nursing
    "تمريض الطوارئ": "hh_n_nursing_department",
    "تمريض الطوارى": "hh_n_nursing_department",
    "تمريض العيادات الخارجية": "hh_n_nursing_department",
    "تمريض العيادات الخارجيه": "hh_n_nursing_department",
    "تمريض غرفة التطعيمات": "hh_n_nursing_department",
    "تمريض غرفة تقديم الأدوية الوريدية (20)": "hh_n_nursing_department",
    "تمريض قسم العمليات": "hh_n_nursing_department",
    "تمريض قسم الافاقة": "hh_n_nursing_department",
    "تمريض قسم الإفاقة": "hh_n_nursing_department",
    "التمريض": "hh_n_nursing_department",
    # Radiology
    "قسم الأشعة": "hh_n_radiology_department",
    "قسم الاشعة": "hh_n_radiology_department",
    "استقبال الأشعة": "hh_n_radiology_department",
    "الأشعة": "hh_n_radiology_department",
    # Operating Rooms
    "قسم العمليات": "hh_n_operating_rooms__or__department",
    # Outpatient / Inpatient administration
    "إدارة التنويم": "hh_n_inpatient_department",
    "اداره التنويم": "hh_n_inpatient_department",
    "مكتب التنويم": "hh_n_inpatient_department",
    "إدارة العيادات الخارجيه": "hh_n_outpatient_department",
    "قسم المواعيد": "hh_n_contact_center_department",
    "قسم السنترال": "hh_n_contact_center_department",
    "قسم تقنية المعلومات": "hh_n_information_technology_department",
    # Housekeeping
    "قسم النظافة": "hh_n_housekeeping___hospitality_department",
    "النظافة": "hh_n_housekeeping___hospitality_department",
    "النظافه": "hh_n_housekeeping___hospitality_department",
    # Security
    "قسم الأمن": "hh_n_security_department",
    "قسم الامن": "hh_n_security_department",
    # Food Services
    "قسم المطبخ": "hh_n_food_services_department",
    "المطبخ": "hh_n_food_services_department",
    "قسم التغذية": "hh_n_food_services_department",
    # Facility Management
    "قسم الصيانة": "hh_n_facility_management___maintenance_department",
    # Executive / Admin
    "المدير المناوب": "hh_n_executive_administration",
    "قسم الإدارة": "hh_n_executive_administration",
    "التنسيق": "hh_n_executive_administration",
    # Social Services
    "قسم الخدمة الإجتماعية": "hh_n_inpatient_department",
    # Patient Affairs
    "قسم علاقات المرضى": "hh_n_patient_affairs_department",
    # Medical Ancillary / Respiratory / Audiology / Neurophysiology
    "فني اختبار السمع": "hh_n_medical_ancillary_services_department",
    "فني تخطيط القلب": "hh_n_medical_ancillary_services_department",
    "فني تخطيط المخ والأعصاب": "hh_n_medical_ancillary_services_department",
    "فني تخطيط المخ والاعصاب": "hh_n_medical_ancillary_services_department",
    "فني دراسة الجهد القلب": "hh_n_medical_ancillary_services_department",
    "قسم العلاج التنفسي": "hh_n_medical_ancillary_services_department",
    # IVF
    "عيادات العقم والإنجاب": "hh_n_ivf",
    # Oncology
    "عيادات جراحة الأورام و الغدد الصماء": "hh_n_oncology_department",
}


# Arabic name → (dept_code, section_name_en)
# Only entries where we can confidently identify the specific section.
# Generic names (e.g. "قسم الصيدلية") are excluded — they map to dept only.
ARABIC_TO_SECTION = {
    # Pharmacy
    "صيدلية الطوارئ": ("hh_n_pharmacy_department", "ER Pharmacy"),
    # Laboratory
    "بنك الدم": ("hh_n_laboratory_department", "Blood Donation & Blood Bank"),
    "استقبال المختبر": ("hh_n_laboratory_department", "Receiving ِArea"),
    # OB/GYN
    "عيادات النساء والولادة": ("hh_n_obstetrics___gynecology_department", "Clinics"),
    "تنويم النساء والولادة": ("hh_n_obstetrics___gynecology_department", "Wards"),
    "تنويم النساء والولاده": ("hh_n_obstetrics___gynecology_department", "Wards"),
    "قسم عمليات الولادة": ("hh_n_obstetrics___gynecology_department", "Labor & Delivery (L&D) / Obstetrics Operating Rooms"),
    "تمريض تنويم النساء والولادة": ("hh_n_obstetrics___gynecology_department", "Wards"),
    # Surgery
    "عيادات جراحة العظام": ("hh_n_surgery_department", "Orthopedic Surgery"),
    "عيادات جراحه العظام": ("hh_n_surgery_department", "Orthopedic Surgery"),
    "قسم جراحة العظام": ("hh_n_surgery_department", "Orthopedic Surgery"),
    "عيادات الجراحة العامة": ("hh_n_surgery_department", "General Surgery"),
    "قسم الجراحة العامة": ("hh_n_surgery_department", "General Surgery"),
    "قسم جراحة المسالك البولية": ("hh_n_surgery_department", "Urology"),
    "عيادات جراحة المسالك البولية": ("hh_n_surgery_department", "Urology"),
    "عيادات جراحة الأنف وأذن وحنجرة": ("hh_n_surgery_department", "ENT"),
    "جراحه الانف واذن وحنجره": ("hh_n_surgery_department", "ENT"),
    "عيادات جراحة الأوعية الدموية": ("hh_n_surgery_department", "Vscular Surgery"),
    "عيادات جراحة المخ والأعصاب": ("hh_n_surgery_department", "Neurosurgery"),
    "عيادات جراحة القفص الصدري": ("hh_n_surgery_department", "Thoracic Surgery"),
    "عيادات جراحة العمود الفقري": ("hh_n_surgery_department", "Spine Surgery"),
    "عيادات جراحة التجميلية": ("hh_n_surgery_department", "Plastic Surgery"),
    "عيادات الجراحة التجميلية": ("hh_n_surgery_department", "Plastic Surgery"),
    "عيادات جراحة سمنة": ("hh_n_surgery_department", "Bariatric"),
    "قسم جراحة السمنة": ("hh_n_surgery_department", "Bariatric"),
    "عيادات جراحة الأورام و الغدد الصماء": ("hh_n_oncology_department", "Hematology"),
    "تمريض تنويم الجراحة العامة": ("hh_n_nursing_department", "Surgical Ward"),
    "تنويم الجراحة العامة": ("hh_n_nursing_department", "Surgical Ward"),
    # Internal Medicine
    "عيادات القلب": ("hh_n_internal_medicine_department", "Cardiology"),
    "عيادات الجهاز الهضمي والمناظير": ("hh_n_internal_medicine_department", "Gastroenterology"),
    "قسم الجهاز الهمضي و الكبد والمناظير": ("hh_n_internal_medicine_department", "Gastroenterology"),
    "قسم الجهاز الهضمي والكبد والمناظير": ("hh_n_internal_medicine_department", "Gastroenterology"),
    "عيادات الصدرية": ("hh_n_internal_medicine_department", "Pulmonology"),
    "عيادات الصدريه": ("hh_n_internal_medicine_department", "Pulmonology"),
    "قسم الصدرية": ("hh_n_internal_medicine_department", "Pulmonology"),
    "عيادات الغدد الصماء": ("hh_n_internal_medicine_department", "Endocrinology"),
    "عيادات المخ والأعصاب": ("hh_n_internal_medicine_department", "Neurology"),
    "عيادات الكلى": ("hh_n_internal_medicine_department", "Nephrology"),
    "عيادات الطب النفسي": ("hh_n_internal_medicine_department", "Psychiatry"),
    "وحدة المناظير": ("hh_n_internal_medicine_department", "Endoscopy"),
    "تمريض تنويم الباطنية": ("hh_n_nursing_department", "Medical Ward"),
    "تنويم الباطنية": ("hh_n_nursing_department", "Medical Ward"),
    "عيادات الباطنية": ("hh_n_internal_medicine_department", "Internal Medicine"),
    # Emergency
    "استقبال الطوارئ": ("hh_n_emergency_administrative_department", "Emergency Reception"),
    "استقبال الطواريء": ("hh_n_emergency_administrative_department", "Emergency Reception"),
    "استقبال العيادات الخارجية": ("hh_n_outpatient_department", "Outpatient Reception"),
    # Critical Care
    "وحدة العناية المركزة": ("hh_n_critical_care_department", "ICU"),
    "تمريض وحدة العناية المركزة": ("hh_n_nursing_department", "ICU/CCU"),
    "وحدة العناية المتوسطة": ("hh_n_critical_care_department", "ICU Stepdown"),
    "تمريض وحدة العناية المتوسطة": ("hh_n_nursing_department", "ICU/CCU Stepdown"),
    "تمريض وحدة طويلي الإقامة": ("hh_n_nursing_department", "LTACU"),
    "وحدة مرضى طويلي الإقامة": ("hh_n_internal_medicine_department", "Long-Term Acute Care Unit (LTACU)"),
    # Nursing
    "تمريض الطوارئ": ("hh_n_nursing_department", "Emergency"),
    "تمريض الطوارى": ("hh_n_nursing_department", "Emergency"),
    "تمريض العيادات الخارجية": ("hh_n_nursing_department", "Outpatient"),
    "تمريض العيادات الخارجيه": ("hh_n_nursing_department", "Outpatient"),
    "تمريض قسم العمليات": ("hh_n_nursing_department", "Main OR"),
    "تمريض قسم الافاقة": ("hh_n_nursing_department", "Recovery"),
    "تمريض قسم الإفاقة": ("hh_n_nursing_department", "Recovery"),
    "تمريض قسم عمليات الولادة": ("hh_n_nursing_department", "OB/OR"),
    # Pediatric
    "تنويم الأطفال": ("hh_n_pediatric_department", "Pediatric Ward"),
    "تنويم الاطفال": ("hh_n_pediatric_department", "Pediatric Ward"),
    "تمريض تنويم الأطفال": ("hh_n_nursing_department", "Pediatric Ward"),
    "تمريض تنويم الاطفال": ("hh_n_nursing_department", "Pediatric Ward"),
    "عيادات الأطفال": ("hh_n_pediatric_department", "General Pediatrics"),
    "وحدة العناية المركزة لحديثي الولادة": ("hh_n_pediatric_department", "NICU"),
    "تمريض وحدة العناية المركزة - أطفال": ("hh_n_nursing_department", "PICU"),
    "وحدة العناية المركزة للأطفال": ("hh_n_pediatric_department", "PICU"),
    "تمريض وحدة العناية لحديثي الولادة": ("hh_n_nursing_department", "NICU"),
    "تمريض الحضانة": ("hh_n_nursing_department", "Nursery"),
    "قسم الحضانة": ("hh_n_pediatric_department", "NURSERY"),
    "عيادات الصدرية (أطفال)": ("hh_n_pediatric_department", "Pediatric Pulmonology"),
    "عيادات جراحة عظام (أطفال)": ("hh_n_pediatric_department", "Pediatric Orthopedic Surgery"),
    "عيادات الأنف والأذن والحنجرة (أطفال)": ("hh_n_pediatric_department", "Pediatric Otolaryngology (ENT)"),
    "عيادات الجهاز الهمضي والمناظير (أطفال)": ("hh_n_pediatric_department", "Pediatric Gastroenterology"),
    "عيادات قلب (أطفال)": ("hh_n_pediatric_department", "Pediatric Cardiology"),
    "عيادات المخ والأعصاب (أطفال)": ("hh_n_pediatric_department", "Pediatric Neurology"),
    "عيادات جراحة المسالك البولية (أطفال)": ("hh_n_pediatric_department", "Pediatric Urology"),
    "عيادات الجراحة العامة (أطفال)": ("hh_n_pediatric_department", "Pediatric General Surgery"),
    "عيادات جراحة الختان": ("hh_n_pediatric_department", "Circumcision"),
    # Outpatient
    "إدارة العيادات الخارجيه": ("hh_n_outpatient_department", "Management"),
    # Medical Ancillary
    "فني اختبار السمع": ("hh_n_medical_ancillary_services_department", "Swallowing Speech and Hearing Unit"),
    "فني تخطيط القلب": ("hh_n_medical_ancillary_services_department", "Cardiac Physiology Services"),
    "فني تخطيط المخ والأعصاب": ("hh_n_medical_ancillary_services_department", "Neurophysiology Services"),
    "فني تخطيط المخ والاعصاب": ("hh_n_medical_ancillary_services_department", "Neurophysiology Services"),
    "فني دراسة الجهد القلب": ("hh_n_medical_ancillary_services_department", "Cardiac Physiology Services"),
    "قسم العلاج الطبيعي": ("hh_n_medical_ancillary_services_department", "Physical Therapy"),
    "استقبال العلاج الطبيعي": ("hh_n_medical_ancillary_services_department", "Physical Therapy"),
    "العلاج الطبيعي": ("hh_n_medical_ancillary_services_department", "Physical Therapy"),
    "قسم العلاج التنفسي": ("hh_n_medical_ancillary_services_department", "Respiratory Therapy"),
    "فني فحص النظر": ("hh_n_medical_ancillary_services_department", "Optometrist Services"),
    "قسم التغذية": ("hh_n_medical_ancillary_services_department", "Clinical Nutrition"),
    # Anesthesia
    "تمريض التخدير": ("hh_n_nursing_department", "Anesthesia"),
    # Radiology
    "استقبال الأشعة": ("hh_n_radiology_department", "General"),
    # Inpatient
    "قسم الخدمة الإجتماعية": ("hh_n_inpatient_department", "Social Worker"),
    # Contact Center
    "قسم المواعيد": ("hh_n_contact_center_department", "Appointment Office"),
    "قسم السنترال": ("hh_n_contact_center_department", "Operator Office"),
    # Dermatology (1 section)
    "عيادات الجلدية": ("hh_n_dermatology_department", "Dermatology"),
    "عيادات الجلديه": ("hh_n_dermatology_department", "Dermatology"),
    # Financial (1 section)
    "قسم المالية": ("hh_n_financial_collection___claims_department", "Financial Collection & Claims"),
    # Security
    "قسم الأمن": ("hh_n_security_department", "Security Guards"),
    "قسم الامن": ("hh_n_security_department", "Security Guards"),
    # Radiology (generic → General)
    "قسم الأشعة": ("hh_n_radiology_department", "General"),
    "قسم الاشعة": ("hh_n_radiology_department", "General"),
    "الأشعة": ("hh_n_radiology_department", "General"),
}


def resolve_department(arabic_name: str, hospital_code: str = "HH-N"):
    """
    Resolve Arabic sub-department name to a Department object.

    Tries exact match first, then normalized match.
    Returns Department instance or None.
    """
    from apps.organizations.models import Department

    if not arabic_name:
        return None

    name = str(arabic_name).strip()

    # Direct lookup
    code = ARABIC_TO_DEPT_CODE.get(name)
    if not code:
        # Try normalized
        normalized = normalize_arabic(name)
        code = ARABIC_TO_DEPT_CODE.get(normalized)

    if not code:
        # Try building a normalized version of all keys
        for key, dept_code in ARABIC_TO_DEPT_CODE.items():
            if normalize_arabic(key) == normalize_arabic(name):
                code = dept_code
                break

    if code:
        try:
            return Department.objects.select_related("hospital").get(
                hospital__code=hospital_code, code=code
            )
        except Department.DoesNotExist:
            return None

    return None


def resolve_section(arabic_name: str, hospital_code: str = "HH-N"):
    """
    Resolve Arabic sub-department name to a (Department, Section) tuple.

    Returns (Department, Section) if section can be identified,
    (Department, None) if only department is known, or (None, None).
    """
    from apps.organizations.models import Department, Section

    if not arabic_name:
        return None, None

    name = str(arabic_name).strip()

    entry = ARABIC_TO_SECTION.get(name)
    if not entry:
        normalized = normalize_arabic(name)
        for key, val in ARABIC_TO_SECTION.items():
            if normalize_arabic(key) == normalized:
                entry = val
                break

    if entry:
        dept_code, section_name = entry
        try:
            dept = Department.objects.select_related("hospital").get(
                hospital__code=hospital_code, code=dept_code
            )
            section = Section.objects.filter(
                department=dept, name_en=section_name
            ).first()
            return dept, section
        except Department.DoesNotExist:
            return None, None

    dept = resolve_department(name, hospital_code)
    return dept, None
