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

One task per (student, KC). Idempotent. MANAGEMENT category.
Standards: Rule 10, Rule 14, ISO/IEC/IEEE 29119-3 5.4, NIST CM-3.
"""
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 STORY tasks to students (one per student per KC)."

    def add_arguments(self, parser):
        parser.add_argument("--students", nargs="+", required=True)
        parser.add_argument("--kc", required=True, help="KC code e.g. C9-CH01-MATTER")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **opts):
        kc_code = opts["kc"].strip().upper()
        kc = KnowledgeComponent.objects.filter(code=kc_code).first()
        if not kc:
            raise CommandError(f"KC not found: {kc_code}")
        self.stdout.write(f"KC: {kc_code}")
        codes = [c.strip().upper() for c in opts["students"] if c.strip()]
        created = skipped_exists = notfound = 0
        with transaction.atomic():
            for code in codes:
                s = Student.objects.filter(code=code).first()
                if not s:
                    self.stderr.write(f"Not found: {code}"); notfound += 1; continue
                if StudentTask.objects.filter(student=s, task_type="STORY",
                                              task_ref=kc_code).exclude(status="SKIPPED").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=s)
                         .first())
                StudentTask.objects.create(
                    student=s, task_type="STORY", task_ref=kc_code,
                    category="MANAGEMENT", status="ASSIGNED",
                    pipeline=_pipe, pipeline_stage=11,
                )
                self.stdout.write(f"  CREATED: {code} -> {kc_code}"); created += 1
        self.stdout.write(f"Created: {created} | Skipped: {skipped_exists} | Notfound: {notfound}")
