"""provision_pipeline_tasks — ensure ACTIVE pipelines have a task at their current student stage.

Fills gaps where the pipeline advanced without creating the next task.
Idempotent. Safe to run repeatedly.

Scope: PAPER-BANK stages (KC_DISCOVERY, KC_TAG) use paper refs like "UR-9".
KC-ref stages (6, 7) and content stages (10, 11) are deferred to their
canonical assigners (assign_kc_tasks, future assign_glossary_tasks_per_book).

Usage:
    python manage.py provision_pipeline_tasks --dry-run
    python manage.py provision_pipeline_tasks --apply
    python manage.py provision_pipeline_tasks --code UR-9-BOOK --apply

Standards: Rule 10 (one canonical provisioner); Rule 4 (verify on disk);
Rule 14 (MANAGEMENT scope); ISO 9001:2015 8.5.1; Google SRE Ch.17.
"""
from django.core.management.base import BaseCommand
from exams.models import TaskPipeline, StudentTask


# Student stages with paper-bank refs. No KC-specific ref needed.
PAPER_BANK_STAGES = {
    3: "KC_DISCOVERY",
    5: "KC_TAG",
}


def _subject_prefix(paper_code):
    """MT-9-BOOK -> MT ; CS-9-BOOK -> CS."""
    return paper_code.split("-")[0].upper()


class Command(BaseCommand):
    help = "Provision missing student-stage tasks for ACTIVE pipelines."

    def add_arguments(self, p):
        p.add_argument("--code", type=str, default=None,
                       help="Limit to one pipeline, e.g. UR-9-BOOK")
        p.add_argument("--apply", action="store_true",
                       help="Actually create rows (default: dry-run)")

    def handle(self, *args, **o):
        qs = (TaskPipeline.objects
              .exclude(status="DONE")
              .order_by("paper_code"))
        if o["code"]:
            qs = qs.filter(paper_code=o["code"].strip().upper())

        created = 0
        skipped = 0
        for p in qs:
            if p.current_stage not in PAPER_BANK_STAGES:
                skipped += 1
                continue
            owner = p.owner_student
            if not owner:
                skipped += 1
                continue
            tt = PAPER_BANK_STAGES[p.current_stage]
            ref = _subject_prefix(p.paper_code) + "-9"
            exists = (StudentTask.objects
                      .filter(student=owner, task_type=tt,
                              task_ref__startswith=ref)
                      .exclude(status="SKIPPED")
                      .exists())
            if exists:
                skipped += 1
                continue
            self.stdout.write(
                "  %s  owner=%s  stage=%d  -> CREATE %s ref=%s"
                % (p.paper_code, owner.code, p.current_stage, tt, ref))
            created += 1
            if o["apply"]:
                StudentTask.objects.create(
                    student=owner, task_type=tt, task_ref=ref,
                    status="ASSIGNED", category="MANAGEMENT",
                    pipeline=p, pipeline_stage=p.current_stage,
                    notes=f"[auto-provision] stage {p.current_stage}",
                )
        self.stdout.write(
            "created=%d skipped=%d applied=%s"
            % (created, skipped, "yes" if o["apply"] else "no (dry-run)"))
