"""unassign_shared_tasks - Rule 25 remediation.

For each MANAGEMENT/SUPPORT task_ref held by more than one student in
an open state, keep the LOWEST-pk row and mark every other row
SKIPPED with a Rule 25 note. Never deletes (Rule 9).

Standards: Rule 25; Rule 9; NIST AI RMF AG-GV.2; ISO 27001 A.8.15.
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import timezone
from exams.models import StudentTask
from exams.ownership import find_violations


class Command(BaseCommand):
    help = "Mark extra MANAGEMENT/SUPPORT task rows SKIPPED (Rule 25)."
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
        p.add_argument("--all-pipelines", action="store_true",
                       help="System-wide sweep. Requires --reason.")
        p.add_argument("--reason", default=None,
                       help="Justification for --all-pipelines (>=20 chars).")
    def handle(self, *a, **o):
        # Turn 5b-1 scope guard (design/ISOLATION-v1.0.md; Rule 28;
        # Saltzer & Schroeder 1975 - fail-safe default)
        if not o.get("all_pipelines"):
            raise CommandError(
                "Refused: this command is system-wide. "
                "Use --all-pipelines --reason '...' (>=20 chars)."
            )
        _reason = (o.get("reason") or "").strip()
        if len(_reason) < 20:
            raise CommandError(
                "--all-pipelines requires --reason with >= 20 chars."
            )
        self.stdout.write("SCOPE: ALL pipelines (reason=" + _reason + ")")
        violations = find_violations()
        self.stdout.write("=== Rule 25 violations (MANAGEMENT/SUPPORT) ===")
        self.stdout.write("  count: " + str(len(violations)))
        for v in violations[:20]:
            self.stdout.write("  " + v["task_ref"] + " -> " + ", ".join(v["students"]))
        if not violations:
            self.stdout.write("(nothing to unassign)")
            return
        if not o["apply"]:
            self.stdout.write("(DRY RUN - pass --apply to mark SKIPPED)")
            return
        now = timezone.now()
        marked = 0
        with transaction.atomic():
            for v in violations:
                rows = (StudentTask.objects
                        .filter(task_ref=v["task_ref"],
                                status__in=["ASSIGNED", "IN_PROGRESS"])
                        .order_by("pk"))
                keeper = rows.first()
                for t in rows[1:]:
                    t.status = "SKIPPED"
                    t.unassigned_at = now
                    t.notes = ((t.notes or "")
                               + "\n[Rule 25 2026-10-08] duplicate of task#"
                               + str(keeper.pk)
                               + " held by " + keeper.student.code).strip()
                    t.save(update_fields=["status", "unassigned_at", "notes"])
                    marked += 1
        self.stdout.write("Applied: " + str(marked) + " rows marked SKIPPED.")
