"""
Management command to set up source-based SLA configs.

Creates MOH and CCHI sources and sets up SLA configurations for all hospitals.
"""
from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.organizations.models import Hospital
from apps.px_sources.models import PXSource
from apps.complaints.models import ComplaintSLAConfig


class Command(BaseCommand):
    help = 'Set up source-based SLA configurations'

    def handle(self, *args, **options):
        self.stdout.write('Setting up source-based SLA configurations...')
        
        # Step 1: Create MOH source
        moh_source, created = PXSource.objects.get_or_create(
            name_en='Ministry of Health',
            defaults={
                'name_ar': 'وزارة الصحة',
                'description': 'Ministry of Health external complaints',
                'is_active': True,
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'✓ Created MOH source: {moh_source.name_en}'))
        else:
            self.stdout.write(self.style.WARNING(f'⊙ MOH source already exists: {moh_source.name_en}'))
        
        # Step 2: Create CCHI source
        cchi_source, created = PXSource.objects.get_or_create(
            name_en='Council of Cooperative Health Insurance',
            defaults={
                'name_ar': 'مجلس التعاون الصحي المشترك',
                'description': 'Council of Cooperative Health Insurance external complaints',
                'is_active': True,
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'✓ Created CCHI source: {cchi_source.name_en}'))
        else:
            self.stdout.write(self.style.WARNING(f'⊙ CCHI source already exists: {cchi_source.name_en}'))
        
        # Get internal sources
        patient_source = PXSource.objects.filter(name_en='Patient').first()
        family_source = PXSource.objects.filter(name_en='Family Member').first()
        staff_source = PXSource.objects.filter(name_en='Staff').first()
        survey_source = PXSource.objects.filter(name_en='Survey').first()
        
        # Step 3: Create SLA configs for each hospital
        hospitals = Hospital.objects.all()
        self.stdout.write(f'\nCreating SLA configs for {hospitals.count()} hospitals...\n')
        
        created_count = 0
        existing_count = 0
        
        for hospital in hospitals:
            self.stdout.write(f'\nHospital: {hospital.name}')
            
            # MOH Config (24 hours SLA)
            moh_config, created = ComplaintSLAConfig.objects.get_or_create(
                hospital=hospital,
                source=moh_source,
                defaults={
                    'sla_hours': 24,
                    'first_reminder_hours_after': 12,  # 12 hours from creation
                    'second_reminder_hours_after': 18,  # 18 hours from creation (6h before SLA)
                    'escalation_hours_after': 24,  # 24 hours from creation
                    'is_active': True,
                }
            )
            if created:
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f'  ✓ MOH SLA Config: {moh_config.sla_hours}h, reminders at {moh_config.first_reminder_hours_after}h/{moh_config.second_reminder_hours_after}h, escalation at {moh_config.escalation_hours_after}h'))
            else:
                existing_count += 1
                self.stdout.write(self.style.WARNING(f'  ⊙ MOH SLA Config already exists'))
            
            # CCHI Config (48 hours SLA)
            cchi_config, created = ComplaintSLAConfig.objects.get_or_create(
                hospital=hospital,
                source=cchi_source,
                defaults={
                    'sla_hours': 48,
                    'first_reminder_hours_after': 24,  # 24 hours from creation
                    'second_reminder_hours_after': 36,  # 36 hours from creation (12h before SLA)
                    'escalation_hours_after': 48,  # 48 hours from creation
                    'is_active': True,
                }
            )
            if created:
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f'  ✓ CCHI SLA Config: {cchi_config.sla_hours}h, reminders at {cchi_config.first_reminder_hours_after}h/{cchi_config.second_reminder_hours_after}h, escalation at {cchi_config.escalation_hours_after}h'))
            else:
                existing_count += 1
                self.stdout.write(self.style.WARNING(f'  ⊙ CCHI SLA Config already exists'))
            
            # Internal Configs (72 hours SLA)
            internal_sources = [
                (patient_source, 'Patient'),
                (family_source, 'Family Member'),
                (staff_source, 'Staff'),
                (survey_source, 'Survey'),
            ]
            
            for source, source_name in internal_sources:
                if source:
                    internal_config, created = ComplaintSLAConfig.objects.get_or_create(
                        hospital=hospital,
                        source=source,
                        defaults={
                            'sla_hours': 72,
                            'first_reminder_hours_after': 24,  # 24 hours from creation
                            'second_reminder_hours_after': 48,  # 48 hours from creation (24h before SLA)
                            'escalation_hours_after': 72,  # 72 hours from creation
                            'is_active': True,
                        }
                    )
                    if created:
                        created_count += 1
                        self.stdout.write(self.style.SUCCESS(f'  ✓ {source_name} SLA Config: {internal_config.sla_hours}h, reminders at {internal_config.first_reminder_hours_after}h/{internal_config.second_reminder_hours_after}h, escalation at {internal_config.escalation_hours_after}h'))
                    else:
                        existing_count += 1
                        self.stdout.write(self.style.WARNING(f'  ⊙ {source_name} SLA Config already exists'))
                else:
                    self.stdout.write(self.style.WARNING(f'  ⚠ {source_name} source not found'))
        
        # Summary
        self.stdout.write('\n' + '='*60)
        self.stdout.write(self.style.SUCCESS(f'Setup complete!'))
        self.stdout.write(f'Created: {created_count} SLA configs')
        self.stdout.write(f'Already existed: {existing_count} SLA configs')
        self.stdout.write('='*60)
        
        self.stdout.write('\nSLA Configuration Summary:')
        self.stdout.write('┌─────────────────────────────────────┬─────────┬──────────┬──────────┬────────────┐')
        self.stdout.write('│ Source                              │ SLA (h) │ 1st Rem  │ 2nd Rem  │ Escalation │')
        self.stdout.write('├─────────────────────────────────────┼─────────┼──────────┼──────────┼────────────┤')
        self.stdout.write('│ Ministry of Health                  │    24   │   12     │   18     │    24      │')
        self.stdout.write('│ Council of Cooperative Health Ins.  │    48   │   24     │   36     │    48      │')
        self.stdout.write('│ Internal (Patient/Family/Staff)     │    72   │   24     │   48     │    72      │')
        self.stdout.write('└─────────────────────────────────────┴─────────┴──────────┴──────────┴────────────┘')