"""Assign GLOSSARY tasks. Section 43 canonical writer (Rule 10).

One task per (student, subject-glossary-KC). Idempotent.

Standards:
  Rule 10 (one canonical writer per task type)
  Rule 14 (MANAGEMENT category)
  ISO/IEC/IEEE 29119-3 5.4 (assign path parity with execute path)
  NIST CM-3 (feature completeness)
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from exams.models import Student, StudentTask, KnowledgeComponent, TaskPipeline


class Command(BaseCommand):
    help = "Assign GLOSSARY tasks to students (one per student per subject)."

    def add_arguments(self, parser):
        parser.add_argument("--students", nargs="+", required=True,
                            help="Student codes e.g. S-0006 S-0009")
        parser.add_argument("--subject", required=True,
                            help="Subject prefix e.g. CH PH MT")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **opts):
        subject = opts["subject"].upper().strip()
        kc_code = f"C9-{subject}00-GLOSSARY"
        kc = KnowledgeComponent.objects.filter(code=kc_code).first()
        if not kc:
            raise CommandError(f"Glossary KC not found: {kc_code}")
        self.stdout.write(f"KC: {kc_code} ({kc.title if hasattr(kc,'title') else ''})")

        codes = [c.strip().upper() for c in opts["students"] if c.strip()]
        created = 0
        skipped_exists = 0
        skipped_notfound = 0

        with transaction.atomic():
            for code in codes:
                student = Student.objects.filter(code=code).first()
                if not student:
                    self.stderr.write(f"Student not found: {code}")
                    skipped_notfound += 1
                    continue
                exists = StudentTask.objects.filter(
                    student=student, task_type="GLOSSARY", task_ref=kc_code,
                ).exclude(status="SKIPPED").exists()
                if exists:
                    self.stdout.write(f"  SKIP (exists): {code}")
                    skipped_exists += 1
                    continue
                if opts["dry_run"]:
                    self.stdout.write(f"  WOULD CREATE: {code} -> {kc_code}")
                    continue
                _pipe = (TaskPipeline.objects
                         .filter(owner_student=student)
                         .first())
                StudentTask.objects.create(
                    student=student,
                    task_type="GLOSSARY",
                    task_ref=kc_code,
                    category="MANAGEMENT",
                    pipeline=_pipe, pipeline_stage=10,
                    status="ASSIGNED",
                )
                self.stdout.write(f"  CREATED: {code} -> {kc_code}")
                created += 1

        self.stdout.write(
            f"Created: {created} | Skipped(exists): {skipped_exists}"
            f" | Not found: {skipped_notfound}"
        )
