"""Expire stale discipline delegations. Idempotent, safe to run hourly.

Standards: ISO 27001 A.5.18 (rights lifecycle); NIST AC-2(3) (inactivity);
ITIL 4 Standard Change; Rule 9 (append-only).
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from discipline.models import DisciplineDelegation, DisciplineAuditEvent
from discipline.services.audit_ops import log_event


class Command(BaseCommand):
    help = "Revoke any active delegation whose expires_at is in the past."

    def handle(self, *args, **opts):
        now = timezone.now()
        qs = DisciplineDelegation.objects.filter(
            revoked_at__isnull=True, expires_at__lte=now)
        n = 0
        for d in qs:
            d.revoked_at = now
            # revoked_by left null; system-triggered expiry is distinct from human revoke
            d.save(update_fields=["revoked_at"])
            try:
                log_event(actor=d.granted_by,
                          action=DisciplineAuditEvent.ACTION_DELEGATION_EXPIRED,
                          delegation=d,
                          target_model="DisciplineDelegation",
                          target_id=d.pk,
                          detail="auto-expire")
            except Exception:
                pass
            n += 1
        self.stdout.write(f"expired: {n}")
