from django.core.management.base import BaseCommand
from django.utils import timezone
from tickets.models import Ticket
from sla.models import SLABreachLog
from notifications.models import Notification


class Command(BaseCommand):
    help = 'Check for SLA breaches and send notifications'

    def handle(self, *args, **kwargs):
        now = timezone.now()
        active = [Ticket.NEW, Ticket.OPEN, Ticket.ASSIGNED, Ticket.IN_PROGRESS, Ticket.ESCALATED]

        breached = Ticket.objects.filter(
            status__in=active,
            resolution_due__lt=now,
            resolution_due__isnull=False,
        )

        new_breaches = 0
        for ticket in breached:
            exists = SLABreachLog.objects.filter(ticket=ticket, breach_type='resolution').exists()
            if not exists:
                minutes_over = int((now - ticket.resolution_due).total_seconds() / 60)
                SLABreachLog.objects.create(
                    ticket=ticket,
                    breach_type='resolution',
                    breach_reason='Automatic breach detection',
                    minutes_overdue=minutes_over,
                )
                if ticket.assigned_agent:
                    Notification.objects.create(
                        recipient=ticket.assigned_agent,
                        notification_type='sla_breach',
                        title=f'SLA Breached: {ticket.ticket_number}',
                        message=f'Ticket {ticket.ticket_number} is {minutes_over} minutes overdue.',
                        ticket=ticket,
                    )
                new_breaches += 1

        # Warning: 80% threshold
        warning_tickets = Ticket.objects.filter(
            status__in=active,
            resolution_due__gt=now,
            resolution_due__isnull=False,
        )
        warnings_sent = 0
        for ticket in warning_tickets:
            if ticket.sla_policy:
                total = ticket.sla_policy.resolution_minutes
                elapsed = (now - ticket.created_at).total_seconds() / 60
                pct = (elapsed / total) * 100 if total else 0
                if pct >= 80:
                    if ticket.assigned_agent:
                        recent = Notification.objects.filter(
                            recipient=ticket.assigned_agent,
                            ticket=ticket,
                            notification_type='sla_warning',
                            created_at__gte=now - timezone.timedelta(hours=1),
                        ).exists()
                        if not recent:
                            Notification.objects.create(
                                recipient=ticket.assigned_agent,
                                notification_type='sla_warning',
                                title=f'SLA Warning: {ticket.ticket_number}',
                                message=f'Ticket {ticket.ticket_number} is at {pct:.0f}% of SLA time.',
                                ticket=ticket,
                            )
                            warnings_sent += 1

        self.stdout.write(
            self.style.SUCCESS(
                f'SLA check complete: {new_breaches} new breaches, {warnings_sent} warnings sent'
            )
        )
