"""
Management command to seed journey stage templates with HIS visit types.

This command creates journey stage templates that match HIS visit types:
- Consultation
- Doctor Visited
- Clinical Condtion
- ChiefComplaint
- Prescribed Drugs

Usage:
    python manage.py seed_journey_stages_his
"""
from django.core.management.base import BaseCommand
from django.db import transaction

from apps.organizations.models import Hospital
from apps.journeys.models import (
    PatientJourneyTemplate,
    PatientJourneyStageTemplate,
    JourneyType
)
from apps.surveys.models import SurveyTemplate


class Command(BaseCommand):
    help = "Seed journey stage templates with HIS visit types"

    def add_arguments(self, parser):
        parser.add_argument(
            "--hospital",
            type=str,
            help="Hospital code to seed (default: all hospitals)",
        )
        parser.add_argument(
            "--survey-template-id",
            type=int,
            help="Survey template ID to attach to stages",
        )

    def handle(self, *args, **options):
        hospital_code = options.get("hospital")
        survey_template_id = options.get("survey-template-id")

        # Get hospitals
        if hospital_code:
            hospitals = Hospital.objects.filter(code=hospital_code)
            if not hospitals.exists():
                self.stdout.write(
                    self.style.ERROR(f"Hospital with code '{hospital_code}' not found")
                )
                return
        else:
            hospitals = Hospital.objects.filter(status="active")

        # Get survey template if provided
        survey_template = None
        if survey_template_id:
            survey_template = SurveyTemplate.objects.filter(id=survey_template_id).first()
            if not survey_template:
                self.stdout.write(
                    self.style.ERROR(f"Survey template with ID {survey_template_id} not found")
                )
                return

        # HIS Visit Types and their mappings
        his_stage_config = [
            {
                'name': 'MD Consultation',
                'code': 'OPD_MD_CONSULT',
                'order': 1,
                'trigger_event_code': 'Consultation',
                'is_active': True
            },
            {
                'name': 'MD Visit',
                'code': 'OPD_MD_VISIT',
                'order': 2,
                'trigger_event_code': 'Doctor Visited',
                'is_active': True
            },
            {
                'name': 'Clinical Assessment',
                'code': 'OPD_CLINICAL',
                'order': 3,
                'trigger_event_code': 'Clinical Condtion',
                'is_active': True
            },
            {
                'name': 'Patient Assessment',
                'code': 'OPD_PATIENT',
                'order': 4,
                'trigger_event_code': 'ChiefComplaint',
                'is_active': True
            },
            {
                'name': 'Pharmacy',
                'code': 'OPD_PHARMACY',
                'order': 5,
                'trigger_event_code': 'Prescribed Drugs',
                'is_active': True
            }
        ]

        total_journeys_updated = 0
        total_stages_created = 0

        for hospital in hospitals:
            self.stdout.write(
                self.style.NOTICE(f"\nProcessing hospital: {hospital.name} ({hospital.code})")
            )

            # Get or create OPD journey template for this hospital
            journey_template, created = PatientJourneyTemplate.objects.get_or_create(
                hospital=hospital,
                journey_type=JourneyType.OPD,
                defaults={
                    "name": f"OPD Patient Journey - {hospital.name}",
                    "description": "Outpatient Department patient journey with HIS integration",
                    "is_active": True,
                    "is_default": True,
                    "send_post_discharge_survey": True if survey_template else False,
                    "post_discharge_survey_delay_hours": 1
                }
            )

            if created:
                self.stdout.write(
                    self.style.SUCCESS(f"  + Created journey template: {journey_template.name}")
                )
                total_journeys_updated += 1
            else:
                self.stdout.write(
                    self.style.WARNING(f"  ! Journey template already exists: {journey_template.name}")
                )
                
                # Update survey template if provided
                if survey_template:
                    journey_template.send_post_discharge_survey = True
                    journey_template.save()
                    self.stdout.write(
                        self.style.SUCCESS(f"  + Updated survey template for journey")
                    )
                    total_journeys_updated += 1

            # Create/update stage templates
            for stage_config in his_stage_config:
                stage_template, stage_created = PatientJourneyStageTemplate.objects.get_or_create(
                    journey_template=journey_template,
                    code=stage_config["code"],
                    defaults={
                        "name": stage_config["name"],
                        "order": stage_config["order"],
                        "is_active": stage_config["is_active"],
                        "survey_template": survey_template,
                        "trigger_event_code": stage_config["trigger_event_code"]
                    }
                )

                if stage_created:
                    self.stdout.write(
                        self.style.SUCCESS(
                            f"  + Created stage: {stage_config['name']} "
                            f"(trigger: {stage_config['trigger_event_code']})"
                        )
                    )
                    total_stages_created += 1
                else:
                    # Update existing stage
                    stage_template.name = stage_config["name"]
                    stage_template.order = stage_config["order"]
                    stage_template.is_active = stage_config["is_active"]
                    if survey_template:
                        stage_template.survey_template = survey_template
                    stage_template.save()
                    self.stdout.write(
                        self.style.WARNING(
                            f"  ! Updated stage: {stage_config['name']} "
                            f"(trigger: {stage_config['trigger_event_code']})"
                        )
                    )

        # Summary
        self.stdout.write(
            self.style.SUCCESS(
                f"\n{'='*60}\n"
                f"Summary:\n"
                f"  Hospitals processed: {hospitals.count()}\n"
                f"  Journey templates created/updated: {total_journeys_updated}\n"
                f"  Stage templates created: {total_stages_created}\n"
                f"{'='*60}\n"
            )
        )
        
        if survey_template:
            self.stdout.write(
                self.style.SUCCESS(
                    f"Survey template attached: {survey_template.name} "
                    f"({survey_template.title_en})"
                )
            )
