"""Delegation query + scope check.

Standards: NIST SP 800-162 (ABAC); NIST SP 800-53 AC-6 (least privilege);
ISO 27001 A.5.18 (access rights lifecycle); Rule 10; Rule 13.
"""
from django.utils import timezone
from discipline.models import DisciplineDelegation


def get_active_delegations(student_user, scope=None):
    """Return active delegations for a user, optionally filtered by scope."""
    qs = DisciplineDelegation.objects.filter(
        student=student_user,
        can_write=True,
        revoked_at__isnull=True,
        expires_at__gt=timezone.now(),
    )
    if scope:
        qs = qs.filter(scope=scope)
    return qs


def has_active_delegation(user, scope, scope_filter=None):
    """True iff user has an active, unexpired, unrevoked grant of `scope`.

    scope_filter: optional dict; if provided, the delegation's scope_filter
    must be a superset of the requested filter (all requested keys match).
    """
    if not getattr(user, "is_authenticated", False):
        return False
    qs = get_active_delegations(user, scope=scope)
    if not scope_filter:
        return qs.exists()
    for d in qs:
        sf = d.scope_filter or {}
        if all(sf.get(k) == v for k, v in scope_filter.items()):
            return True
    return False
