"""restore_unassigned_mgmt — restore MANAGEMENT tasks hidden by mistake.

Problem: a bulk unassign (2026-10-10) set unassigned_at on tasks that
should still be live (status ASSIGNED/IN_PROGRESS at or before their
pipeline's current stage). Those tasks are invisible to students even
though the pipeline expects them to be done.

Scope (narrow on purpose):
  - category == MANAGEMENT only (ACADEMIC is by design unassigned when
    the teacher pauses drills)
  - status in {ASSIGNED, IN_PROGRESS}
  - unassigned_at is NOT NULL
  - pipeline exists AND pipeline_stage <= pipeline.current_stage

Clears unassigned_at. Idempotent. Dry-run by default.

Standards:
  ISO 8000-61 (data fit for purpose)
  ALCOA+ Accurate
  Saltzer & Schroeder 1975 (fail-safe: show the work)
  Rule 9 (log, don't delete)
  Rule 14 (MANAGEMENT is per-pipeline)
  Rule 23 (one job)
  Rule 24 (sandbox first)
  Rule 28 (standards supremacy)

Usage:
  python manage.py restore_unassigned_mgmt
  python manage.py restore_unassigned_mgmt --apply
  python manage.py restore_unassigned_mgmt --student S-0015 --apply
"""
from django.core.management.base import BaseCommand
from django.utils import timezone

from exams.models import StudentTask, TaskPipeline, PortalFeatureLog


class Command(BaseCommand):
    help = "Clear unassigned_at on MANAGEMENT tasks at or before current stage. Dry-run default."

    def add_arguments(self, parser):
        parser.add_argument("--apply", action="store_true",
                            help="Actually clear unassigned_at (default: dry-run).")
        parser.add_argument("--student", dest="student", default="",
                            help="Restrict to one student code (e.g. S-0015).")
        parser.add_argument("--limit", type=int, default=0,
                            help="Stop after N candidates (0 = no limit).")

    def handle(self, *args, **options):
        apply = options["apply"]
        student_code = (options["student"] or "").strip().upper()
        limit = int(options["limit"] or 0)

        pipe_stages = {p.id: p.current_stage for p in TaskPipeline.objects.all()}

        qs = StudentTask.objects.filter(
            category="MANAGEMENT",
            status__in=["ASSIGNED", "IN_PROGRESS"],
            unassigned_at__isnull=False,
            pipeline__isnull=False,
        ).select_related("student", "pipeline").order_by("student__code", "id")

        if student_code:
            qs = qs.filter(student__code=student_code)

        candidates = []
        for t in qs:
            cur = pipe_stages.get(t.pipeline_id)
            if cur is None:
                continue
            if t.pipeline_stage is None:
                continue
            if t.pipeline_stage <= cur:
                candidates.append(t)
                if limit and len(candidates) >= limit:
                    break

        self.stdout.write("=== restore_unassigned_mgmt ===")
        self.stdout.write("mode: " + ("APPLY" if apply else "DRY-RUN"))
        if student_code:
            self.stdout.write("student: " + student_code)
        self.stdout.write("candidates: " + str(len(candidates)))
        self.stdout.write("")
        for t in candidates:
            self.stdout.write("  id=%s | %s | %s | ref=%s | stage=%s/%s | pipe=%s" % (
                t.id, t.student.code, t.task_type, t.task_ref,
                t.pipeline_stage, pipe_stages.get(t.pipeline_id),
                t.pipeline.paper_code if t.pipeline else "?",
            ))

        if not candidates:
            self.stdout.write("")
            self.stdout.write(self.style.SUCCESS("nothing to restore"))
            return

        if not apply:
            self.stdout.write("")
            self.stdout.write("(dry-run - pass --apply to write)")
            return

        now = timezone.now()
        restored = 0
        for t in candidates:
            old_note = t.notes or ""
            marker = "[restore_unassigned_mgmt " + now.isoformat()[:19] + "]"
            t.unassigned_at = None
            new_note = (old_note + ("\n" if old_note else "") + marker +
                        " unassigned_at cleared (was hidden; stage <= current)")
            t.notes = new_note[:4000]
            t.save(update_fields=["unassigned_at", "notes"])
            PortalFeatureLog.objects.create(
                key="restore_unassigned_mgmt." + t.student.code,
                old_enabled=False, new_enabled=True,
                changed_by=None,
                note="task " + str(t.id) + " unassigned_at cleared ("
                     + t.task_type + " " + t.task_ref + ")",
            )
            restored += 1

        self.stdout.write("")
        self.stdout.write(self.style.SUCCESS(
            "restored: " + str(restored) + " tasks"))
