from django.core.management.base import BaseCommand
from apps.surveys.models import SurveyTemplate, SurveyQuestion, QuestionType
from apps.organizations.models import Hospital


class Command(BaseCommand):
    help = 'Create survey templates for all HIS patient types'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Creating HIS Survey Templates...'))
        
        # Get active hospital
        hospital = Hospital.objects.filter(status='active').first()
        if not hospital:
            self.stdout.write(self.style.ERROR('No active hospital found!'))
            return
        
        self.stdout.write(f'Using hospital: {hospital.name}')
        
        # Define survey templates for each patient type
        survey_templates = [
            {
                'name': 'Inpatient Post-Discharge Survey',
                'survey_type': 'stage',
                'questions': [
                    'How satisfied were you with the nursing care?',
                    'How satisfied were you with the doctor\'s care?',
                    'How clean was your room?',
                    'How satisfied were you with the food quality?',
                    'How well were you informed about your treatment?',
                    'How likely are you to recommend this hospital to others?',
                    'Any additional comments or suggestions?'
                ]
            },
            {
                'name': 'OPD Patient Experience Survey',
                'survey_type': 'stage',
                'questions': [
                    'How satisfied were you with the registration process?',
                    'How satisfied were you with the waiting time?',
                    'How satisfied were you with the doctor\'s consultation?',
                    'How satisfied were you with the pharmacy service?',
                    'How likely are you to recommend this hospital to others?',
                    'Any additional comments or suggestions?'
                ]
            },
            {
                'name': 'EMS Emergency Services Survey',
                'survey_type': 'stage',
                'questions': [
                    'How satisfied were you with the ambulance response time?',
                    'How satisfied were you with the paramedic care?',
                    'How satisfied were you with the emergency department care?',
                    'How satisfied were you with the communication from staff?',
                    'How likely are you to recommend this hospital to others?',
                    'Any additional comments or suggestions?'
                ]
            },
            {
                'name': 'Day Case Patient Survey',
                'survey_type': 'stage',
                'questions': [
                    'How satisfied were you with the pre-procedure preparation?',
                    'How satisfied were you with the procedure itself?',
                    'How satisfied were you with the post-procedure care?',
                    'How satisfied were you with the discharge process?',
                    'How likely are you to recommend this hospital to others?',
                    'Any additional comments or suggestions?'
                ]
            }
        ]
        
        created_count = 0
        updated_count = 0
        
        for template_data in survey_templates:
            # Check if template already exists
            existing = SurveyTemplate.objects.filter(
                name=template_data['name'],
                hospital=hospital
            ).first()
            
            if existing:
                self.stdout.write(f'✓ Template already exists: {template_data["name"]}')
                updated_count += 1
                template = existing
            else:
                # Create new template
                template = SurveyTemplate.objects.create(
                    name=template_data['name'],
                    hospital=hospital,
                    survey_type=template_data['survey_type'],
                    is_active=True
                )
                self.stdout.write(f'✓ Created template: {template_data["name"]}')
                created_count += 1
            
            # Create/update questions
            for order, question_text in enumerate(template_data['questions'], start=1):
                # Create question directly
                survey_question, created = SurveyQuestion.objects.get_or_create(
                    survey_template=template,
                    text=question_text,
                    defaults={
                        'question_type': QuestionType.RATING if 'How likely' in question_text else QuestionType.TEXT,
                        'order': order,
                        'is_required': True
                    }
                )
                
                if created:
                    self.stdout.write(f'  ✓ Added question: {question_text[:50]}...')
        
        self.stdout.write(self.style.SUCCESS(
            f'\n✓ Survey Templates created/updated successfully!\n'
            f'  Created: {created_count}\n'
            f'  Updated: {updated_count}\n'
            f'  Total: {len(survey_templates)}'
        ))
        
        # List all templates
        self.stdout.write('\nAll Active Survey Templates:')
        for template in SurveyTemplate.objects.filter(is_active=True):
            self.stdout.write(f'  - {template.name} (Type: {template.survey_type}, Questions: {template.get_question_count()})')
