from uuid import UUID
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError, PermissionDenied
from django.core.management.base import BaseCommand, CommandError
from apps.sla.services import monitor
from apps.sla.queries import centers


class Command(BaseCommand):
    help = "Enroll applicable cases, record SLA escalations, and queue configured alerts. Never dispatch messages."

    def add_arguments(self, parser):
        parser.add_argument("--actor", type=UUID, required=True, help="Active authorized user UUID (also records system origin).")
        parser.add_argument("--company", type=UUID)
        parser.add_argument("--center", type=UUID)

    def handle(self, *args, **options):
        actor = get_user_model().objects.filter(pk=options["actor"], is_active=True).first()
        allowed = centers(actor, "sla.monitor_sla")
        if options["company"]:
            allowed = allowed.filter(company_id=options["company"])
        if options["center"]:
            allowed = allowed.filter(pk=options["center"])
        if actor is None or not allowed.exists():
            raise CommandError("No authorized monitoring scope.")
        try:
            counts = monitor(actor=actor, company_id=options["company"], service_center_id=options["center"])
        except (ValidationError, PermissionDenied) as error:
            raise CommandError(str(error)) from error
        self.stdout.write("SLA monitoring: " + ", ".join(f"{key}={value}" for key, value in counts.items()))
