"""
Management command to seed journey templates and surveys for HIS simulator.

This command creates:
1. Journey templates (EMS, Inpatient, OPD) with random stages
2. Survey templates with questions for each journey type
3. Associates surveys with journey stages
"""
import random
from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.journeys.models import (
    JourneyType,
    PatientJourneyTemplate,
    PatientJourneyStageTemplate
)
from apps.surveys.models import (
    SurveyTemplate,
    SurveyQuestion,
    QuestionType,
)
from apps.organizations.models import Hospital, Department


class Command(BaseCommand):
    help = 'Seed journey templates and surveys for HIS simulator'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed journey templates and surveys...'))

        # Get or create a default hospital
        from apps.core.models import StatusChoices
        hospital, _ = Hospital.objects.get_or_create(
            code='ALH-main',
            defaults={
                'name': 'Al Hammadi Hospital',
                'name_ar': 'مستشفى الحمادي',
                'city': 'Riyadh',
                'status': StatusChoices.ACTIVE
            }
        )

        # Get or create some departments
        departments = self.get_or_create_departments(hospital)

        # Create journey templates and surveys
        self.create_ems_journey(hospital, departments)
        self.create_inpatient_journey(hospital, departments)
        self.create_opd_journey(hospital, departments)

        self.stdout.write(self.style.SUCCESS('✓ Successfully seeded journey templates and surveys!'))

    def get_or_create_departments(self, hospital):
        """Get or create departments for the hospital"""
        departments = {}
        dept_data = [
            ('EMERGENCY', 'Emergency Department', 'قسم الطوارئ'),
            ('CARDIOLOGY', 'Cardiology', 'أمراض القلب'),
            ('ORTHO', 'Orthopedics', 'جراحة العظام'),
            ('PEDS', 'Pediatrics', 'طب الأطفال'),
            ('LAB', 'Laboratory', 'المختبر'),
            ('RADIO', 'Radiology', 'الأشعة'),
            ('PHARMACY', 'Pharmacy', 'الصيدلية'),
            ('NURSING', 'Nursing', 'التمريض'),
        ]

        for code, name_en, name_ar in dept_data:
            from apps.core.models import StatusChoices
            dept, _ = Department.objects.get_or_create(
                hospital=hospital,
                code=code,
                defaults={
                    'name': name_en,
                    'name_ar': name_ar,
                    'status': StatusChoices.ACTIVE
                }
            )
            departments[code] = dept

        return departments

    def create_ems_journey(self, hospital, departments):
        """Create EMS journey template with random stages (2-4 stages)"""
        self.stdout.write('\nCreating EMS journey...')

        # Create survey template
        survey_template = SurveyTemplate.objects.create(
            name='EMS Experience Survey',
            name_ar='استبيان تجربة الطوارئ',
            hospital=hospital,
            is_active=True
        )

        # Add survey questions
        questions = [
            ('How satisfied were you with the ambulance arrival time?', 'كم كنت راضيًا عن وقت وصول الإسعاف?'),
            ('How would you rate the ambulance staff professionalism?', 'كيف تقيم احترافية طاقم الإسعاف?'),
            ('Did the ambulance staff explain what they were doing?', 'هل شرح طاقم الإسعاف ما كانوا يفعلونه?'),
            ('How was the overall ambulance experience?', 'كيف كانت تجربة الإسعاف بشكل عام?'),
        ]

        for i, (q_en, q_ar) in enumerate(questions, 1):
            SurveyQuestion.objects.create(
                survey_template=survey_template,
                text=q_en,
                text_ar=q_ar,
                question_type=QuestionType.RATING,
                order=i,
                is_required=True
            )

        # Create journey template
        journey_template = PatientJourneyTemplate.objects.create(
            name='EMS Patient Journey',
            name_ar='رحلة المريض للطوارئ',
            journey_type=JourneyType.EMS,
            description='Emergency medical services patient journey',
            hospital=hospital,
            is_active=True,
            is_default=True,
            send_post_discharge_survey=True,
            post_discharge_survey_delay_hours=1
        )

        # Create random stages (2-4 stages)
        num_stages = random.randint(2, 4)
        stage_templates = [
            ('Ambulance Dispatch', 'إرسال الإسعاف', 'EMS_STAGE_1_DISPATCHED'),
            ('On Scene Care', 'الرعاية في الموقع', 'EMS_STAGE_2_ON_SCENE'),
            ('Patient Transport', 'نقل المريض', 'EMS_STAGE_3_TRANSPORT'),
            ('Hospital Handoff', 'تسليم المستشفى', 'EMS_STAGE_4_HANDOFF'),
        ]

        for i in range(num_stages):
            stage_template = PatientJourneyStageTemplate.objects.create(
                journey_template=journey_template,
                name=stage_templates[i][0],
                name_ar=stage_templates[i][1],
                code=stage_templates[i][2],
                order=i + 1,
                trigger_event_code=stage_templates[i][2],
                survey_template=survey_template,
                is_optional=False,
                is_active=True
            )

        self.stdout.write(self.style.SUCCESS(f'  ✓ EMS journey created with {num_stages} stages'))

    def create_inpatient_journey(self, hospital, departments):
        """Create Inpatient journey template with random stages (3-6 stages)"""
        self.stdout.write('\nCreating Inpatient journey...')

        # Create survey template
        survey_template = SurveyTemplate.objects.create(
            name='Inpatient Experience Survey',
            name_ar='استبيان تجربة المرضى الداخليين',
            hospital=hospital,
            is_active=True
        )

        # Add survey questions
        questions = [
            ('How satisfied were you with the admission process?', 'كم كنت راضيًا عن عملية القبول?'),
            ('How would you rate the nursing care you received?', 'كيف تقيم الرعاية التمريضية التي تلقيتها?'),
            ('Did the doctors explain your treatment clearly?', 'هل أوضح الأطباء علاجك بوضوح?'),
            ('How clean and comfortable was your room?', 'كم كانت نظافة وراحة غرفتك?'),
            ('How satisfied were you with the food service?', 'كم كنت راضيًا عن خدمة الطعام?'),
            ('How would you rate the discharge process?', 'كيف تقيم عملية الخروج?'),
            ('Would you recommend this hospital to others?', 'هل ستنصح هذا المستشفى للآخرين?'),
        ]

        for i, (q_en, q_ar) in enumerate(questions, 1):
            SurveyQuestion.objects.create(
                survey_template=survey_template,
                text=q_en,
                text_ar=q_ar,
                question_type=QuestionType.RATING,
                order=i,
                is_required=True
            )

        # Create journey template
        journey_template = PatientJourneyTemplate.objects.create(
            name='Inpatient Patient Journey',
            name_ar='رحلة المريض الداخلي',
            journey_type=JourneyType.INPATIENT,
            description='Inpatient journey from admission to discharge',
            hospital=hospital,
            is_active=True,
            is_default=True,
            send_post_discharge_survey=True,
            post_discharge_survey_delay_hours=24
        )

        # Create random stages (3-6 stages)
        num_stages = random.randint(3, 6)
        stage_templates = [
            ('Admission', 'القبول', 'INPATIENT_STAGE_1_ADMISSION'),
            ('Treatment', 'العلاج', 'INPATIENT_STAGE_2_TREATMENT'),
            ('Nursing Care', 'الرعاية التمريضية', 'INPATIENT_STAGE_3_NURSING'),
            ('Lab Tests', 'الفحوصات المخبرية', 'INPATIENT_STAGE_4_LAB'),
            ('Radiology', 'الأشعة', 'INPATIENT_STAGE_5_RADIOLOGY'),
            ('Discharge', 'الخروج', 'INPATIENT_STAGE_6_DISCHARGE'),
        ]

        for i in range(num_stages):
            stage_template = PatientJourneyStageTemplate.objects.create(
                journey_template=journey_template,
                name=stage_templates[i][0],
                name_ar=stage_templates[i][1],
                code=stage_templates[i][2],
                order=i + 1,
                trigger_event_code=stage_templates[i][2],
                survey_template=survey_template,
                is_optional=False,
                is_active=True
            )

        self.stdout.write(self.style.SUCCESS(f'  ✓ Inpatient journey created with {num_stages} stages'))

    def create_opd_journey(self, hospital, departments):
        """Create OPD journey template with random stages (3-5 stages)"""
        self.stdout.write('\nCreating OPD journey...')

        # Create survey template
        survey_template = SurveyTemplate.objects.create(
            name='OPD Experience Survey',
            name_ar='استبيان تجربة العيادات الخارجية',
            hospital=hospital,
            is_active=True
        )

        # Add survey questions
        questions = [
            ('How satisfied were you with the registration process?', 'كم كنت راضيًا عن عملية التسجيل?'),
            ('How long did you wait to see the doctor?', 'كم مدة انتظارك لرؤية الطبيب?'),
            ('Did the doctor listen to your concerns?', 'هل استمع الطبيب لمخاوفك?'),
            ('Did the doctor explain your diagnosis and treatment?', 'هل أوضح الطبيب تشخيصك وعلاجك?'),
            ('How satisfied were you with the lab services?', 'كم كنت راضيًا عن خدمات المختبر?'),
            ('How satisfied were you with the pharmacy services?', 'كم كنت راضيًا عن خدمات الصيدلية?'),
            ('How would you rate your overall visit experience?', 'كيف تقيم تجربة زيارتك بشكل عام?'),
        ]

        for i, (q_en, q_ar) in enumerate(questions, 1):
            SurveyQuestion.objects.create(
                survey_template=survey_template,
                text=q_en,
                text_ar=q_ar,
                question_type=QuestionType.RATING,
                order=i,
                is_required=True
            )

        # Create journey template
        journey_template = PatientJourneyTemplate.objects.create(
            name='OPD Patient Journey',
            name_ar='رحلة المريض للعيادات الخارجية',
            journey_type=JourneyType.OPD,
            description='Outpatient department patient journey',
            hospital=hospital,
            is_active=True,
            is_default=True,
            send_post_discharge_survey=True,
            post_discharge_survey_delay_hours=2
        )

        # Create random stages (3-5 stages)
        num_stages = random.randint(3, 5)
        stage_templates = [
            ('Registration', 'التسجيل', 'OPD_STAGE_1_REGISTRATION'),
            ('Consultation', 'الاستشارة', 'OPD_STAGE_2_CONSULTATION'),
            ('Lab Tests', 'الفحوصات المخبرية', 'OPD_STAGE_3_LAB'),
            ('Radiology', 'الأشعة', 'OPD_STAGE_4_RADIOLOGY'),
            ('Pharmacy', 'الصيدلية', 'OPD_STAGE_5_PHARMACY'),
        ]

        for i in range(num_stages):
            stage_template = PatientJourneyStageTemplate.objects.create(
                journey_template=journey_template,
                name=stage_templates[i][0],
                name_ar=stage_templates[i][1],
                code=stage_templates[i][2],
                order=i + 1,
                trigger_event_code=stage_templates[i][2],
                survey_template=survey_template,
                is_optional=False,
                is_active=True
            )

        self.stdout.write(self.style.SUCCESS(f'  ✓ OPD journey created with {num_stages} stages'))
