"""
Management command to seed default observation SLA configs with department response settings.

Usage:
    python manage.py seed_observation_dept_response_sla
    python manage.py seed_observation_dept_response_sla --hospital-id=<uuid>
"""
from django.core.management.base import BaseCommand

from apps.observations.models import ObservationSLAConfig
from apps.organizations.models import Hospital


class Command(BaseCommand):
    help = 'Seed default observation SLA configs with department response SLA settings'

    def add_arguments(self, parser):
        parser.add_argument(
            '--hospital-id',
            type=str,
            help='Specific hospital ID to seed configs for',
        )

    def handle(self, *args, **options):
        hospital_id = options.get('hospital_id')

        if hospital_id:
            try:
                hospitals = [Hospital.objects.get(id=hospital_id)]
            except Hospital.DoesNotExist:
                self.stdout.write(self.style.ERROR(f"Hospital with ID {hospital_id} not found"))
                return
        else:
            hospitals = Hospital.objects.filter(status='active')

        updated_count = 0
        created_count = 0

        for hospital in hospitals:
            configs = ObservationSLAConfig.objects.filter(hospital=hospital, is_active=True)
            found = False
            for config in configs:
                config.dept_response_hours = 48
                config.dept_response_reminder_hours_before = 12
                config.dept_response_second_reminder_enabled = True
                config.dept_response_second_reminder_hours_before = 4
                config.dept_response_auto_escalate_enabled = True
                config.dept_response_escalation_hours_overdue = 0
                config.save()
                updated_count += 1
                found = True

            if not found:
                config = ObservationSLAConfig.objects.create(
                    hospital=hospital,
                    severity=None,
                    sla_hours=72,
                    reminder_hours_before=24,
                    dept_response_hours=48,
                    dept_response_reminder_hours_before=12,
                    dept_response_second_reminder_enabled=True,
                    dept_response_second_reminder_hours_before=4,
                    dept_response_auto_escalate_enabled=True,
                    dept_response_escalation_hours_overdue=0,
                    is_active=True,
                )
                created_count += 1

        self.stdout.write(
            self.style.SUCCESS(
                f'Seeded observation dept response SLA: {updated_count} updated, {created_count} created'
            )
        )
