"""Rule 25 ownership guard.

Row level (always):     one StudentTask row -> exactly one Student FK.
task_ref level:         MANAGEMENT / SUPPORT tasks are exclusive per
                        task_ref; ACADEMIC tasks are per-student copies
                        by design (Rule 14; MTSS/NCII).

Standards: Rule 25; Rule 14; NIST AI RMF AG-GV.2;
AERA/APA/NCME 2014 Std 1.0 + 13.7.
"""
from collections import defaultdict

EXCLUSIVE_CATEGORIES = ("MANAGEMENT", "SUPPORT")
OPEN_STATES = ("ASSIGNED", "IN_PROGRESS")


def check_unique_owner(task_ref, student, category):
    """Return (ok, conflicting_student_code_or_None).

    ACADEMIC returns (True, None) - per-student copies are by design.
    MANAGEMENT / SUPPORT returns (False, code) if a different student
    already holds an open row with the same task_ref.
    """
    if category not in EXCLUSIVE_CATEGORIES:
        return True, None
    from exams.models import StudentTask
    other = (StudentTask.objects
             .filter(task_ref=task_ref, status__in=OPEN_STATES)
             .exclude(student=student)
             .order_by("pk")
             .first())
    if other is None:
        return True, None
    return False, other.student.code


def find_violations():
    """Return list of dicts describing MANAGEMENT/SUPPORT task_refs
    currently held by more than one student in an open state."""
    from exams.models import StudentTask
    buckets = defaultdict(set)
    qs = (StudentTask.objects
          .filter(status__in=OPEN_STATES, category__in=EXCLUSIVE_CATEGORIES)
          .values_list("task_ref", "student__code"))
    for ref, code in qs:
        buckets[ref].add(code)
    return [{"task_ref": ref, "students": sorted(codes)}
            for ref, codes in buckets.items() if len(codes) > 1]
