"""backfill_pipelines — create TaskPipeline rows for students with live MGMT
tasks but no pipeline.

Derives the book from ANY live management task ref:
    "MT-9-BOOK#p=1-2"     -> MT
    "MT-9"                -> MT
    "MT-9#..."            -> MT
    "C9-MT01-RADICALS"    -> MT  (strip "C9-")
    "C9-CH00-GLOSSARY"    -> CH
The most common subject across a student's live tasks wins.

Idempotent. Dry-run by default.

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


def _subject_from_ref(ref):
    """Extract the two-letter subject prefix from any management task_ref."""
    if not ref:
        return None
    # Strip #fragment
    ref = ref.split("#", 1)[0].strip().upper()
    if not ref:
        return None
    # BOOK_INGEST / KC_DISCOVERY / KC_TAG: "MT-9-BOOK" or "MT-9"
    if "-9" in ref:
        head = ref.split("-", 1)[0]
        if 2 <= len(head) <= 3 and head.isalpha():
            return head
    # KC_* : "C9-MT01-RADICALS"
    if ref.startswith("C9-"):
        rest = ref[3:]
        letters = "".join(c for c in rest[:2] if c.isalpha())
        if len(letters) == 2:
            return letters
    return None


class Command(BaseCommand):
    help = "Create missing TaskPipeline rows from any live MANAGEMENT task."

    def add_arguments(self, p):
        p.add_argument("--code", type=str, default=None)
        p.add_argument("--apply", action="store_true")

    def handle(self, *args, **o):
        students_qs = Student.objects.filter(is_active=True).order_by("code")
        if o["code"]:
            students_qs = students_qs.filter(code=o["code"].strip().upper())

        created = 0
        skipped = 0
        for s in students_qs:
            if TaskPipeline.objects.filter(owner_student=s).exists():
                skipped += 1
                continue
            live = (StudentTask.objects
                    .filter(student=s, category="MANAGEMENT")
                    .exclude(status__in=["DONE", "SKIPPED"])
                    .exclude(unassigned_at__isnull=False))
            if not live.exists():
                skipped += 1
                continue
            subjects = Counter()
            for t in live:
                subj = _subject_from_ref(t.task_ref or "")
                if subj:
                    subjects[subj] += 1
            if not subjects:
                skipped += 1
                continue
            subj = subjects.most_common(1)[0][0]
            book = subj + "-9-BOOK"
            self.stdout.write(
                "  %s %s -> CREATE pipeline %s (from %d live tasks, subjects=%s)"
                % (s.code, s.name[:18], book, live.count(), dict(subjects)))
            created += 1
            if o["apply"]:
                TaskPipeline.objects.create(
                    paper_code=book,
                    owner_student=s,
                    current_stage=1,
                    stages_completed=[],
                    status="ACTIVE",
                )
        self.stdout.write(
            "created=%d skipped=%d applied=%s"
            % (created, skipped, "yes" if o["apply"] else "no (dry-run)"))
