from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.surveys.models import SurveyTemplate, SurveyQuestion
from apps.integrations.models import SurveyTemplateMapping
from apps.organizations.models import Hospital
from django.db import transaction


class Command(BaseCommand):
    help = "Seed survey template mappings for HIS integration"

    SATISFACTION_OPTIONS = ["Very Unsatisfied", "Poor", "Neutral", "Good", "Very Satisfied"]

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS("Seeding survey template mappings..."))

        # Get or create satisfaction surveys
        inpatient_survey = self.get_or_create_satisfaction_survey(
            "Inpatient Satisfaction Survey", "How satisfied were you with your inpatient stay?"
        )

        outpatient_survey = self.get_or_create_satisfaction_survey(
            "Outpatient Satisfaction Survey", "How satisfied were you with your outpatient visit?"
        )

        appointment_survey = self.get_or_create_satisfaction_survey(
            "Appointment Satisfaction Survey", "How satisfied were you with your appointment?"
        )

        # Create mappings for patient types
        self.create_or_update_mapping("IP", inpatient_survey, "Inpatient")
        self.create_or_update_mapping("OP", outpatient_survey, "Outpatient")
        self.create_or_update_mapping("ED", appointment_survey, "Emergency")

        self.stdout.write(self.style.SUCCESS("Survey template mappings seeded successfully!"))
        self.stdout.write("\nSurvey Templates:")
        self.stdout.write(f"  - Inpatient: {inpatient_survey.name} (ID: {inpatient_survey.id})")
        self.stdout.write(f"  - Outpatient: {outpatient_survey.name} (ID: {outpatient_survey.id})")
        self.stdout.write(f"  - Appointment: {appointment_survey.name} (ID: {appointment_survey.id})")

    def get_or_create_satisfaction_survey(self, name, question_text):
        """Get or create a satisfaction survey with multiple choice question"""
        survey = SurveyTemplate.objects.filter(name=name).first()

        if not survey:
            self.stdout.write(f"Creating survey: {name}")
            # Get first hospital (default)
            hospital = Hospital.objects.first()
            if not hospital:
                self.stdout.write(self.style.ERROR("No hospital found! Please create a hospital first."))
                return None

            survey = SurveyTemplate.objects.create(
                name=name, name_ar=name, hospital=hospital, survey_type="general", is_active=True
            )

            # Create the satisfaction question with choices
            choices = []
            for idx, option_text in enumerate(self.SATISFACTION_OPTIONS, 1):
                choices.append({"value": str(idx), "label": option_text, "label_ar": option_text})

            question = SurveyQuestion.objects.create(
                survey_template=survey,
                text=question_text,
                question_type="multiple_choice",
                order=1,
                is_required=True,
                choices_json=choices,
            )

            self.stdout.write(f"  Created question: {question_text}")
            self.stdout.write(f"  Added {len(self.SATISFACTION_OPTIONS)} satisfaction options")
        else:
            # Ensure the question has correct options
            self.update_satisfaction_question(survey)
            self.stdout.write(f"Found existing survey: {name}")

        return survey

    def update_satisfaction_question(self, survey):
        """Update survey question to ensure it has correct satisfaction options"""
        question = survey.questions.filter(question_type="multiple_choice").first()

        if not question:
            self.stdout.write(f"  Warning: No multiple choice question found in {survey.name}")
            return

        # Check if all options exist
        existing_choices = question.choices_json or []
        existing_labels = {choice["label"] for choice in existing_choices}
        required_options = set(self.SATISFACTION_OPTIONS)

        if existing_labels == required_options:
            self.stdout.write(f"  Question has correct satisfaction options")
            return

        # Rebuild choices with all required options
        choices = []
        for idx, option_text in enumerate(self.SATISFACTION_OPTIONS, 1):
            # Find existing choice if it exists
            existing_choice = next((c for c in existing_choices if c["label"] == option_text), None)
            if existing_choice:
                choices.append(existing_choice)
            else:
                choices.append({"value": str(idx), "label": option_text, "label_ar": option_text})

        question.choices_json = choices
        question.save()
        self.stdout.write(f"  Updated question with correct satisfaction options")

    def create_or_update_mapping(self, patient_type, survey_template, description):
        """Create or update a survey template mapping"""
        mapping = SurveyTemplateMapping.objects.filter(patient_type=patient_type, is_active=True).first()

        if mapping:
            if mapping.survey_template != survey_template:
                mapping.survey_template = survey_template
                mapping.save()
                self.stdout.write(f"Updated mapping for {description}: {survey_template.name}")
            else:
                self.stdout.write(f"Existing mapping for {description}: {survey_template.name}")
        else:
            # Deactivate existing mappings for this patient type
            SurveyTemplateMapping.objects.filter(patient_type=patient_type).update(is_active=False)

            # Create new active mapping
            mapping = SurveyTemplateMapping.objects.create(
                patient_type=patient_type, survey_template=survey_template, is_active=True
            )
            self.stdout.write(f"Created mapping for {description}: {survey_template.name}")
