"""pipeline_health_check — per-student pipeline diagnostic.

Walks every active student and reports:
  - login + token presence
  - TaskPipeline rows
  - orphan refs (task_ref points to nothing)
  - every live task's prompt loads without error
  - unsubstituted placeholders (__KC_CODE__ etc.)

Standards: ISO/IEC/IEEE 29119-3 5.4; Rule 4; Rule 26; NIST CM-3.
"""
from collections import Counter
from django.core.management.base import BaseCommand
from exams.models import (Student, StudentTask, TaskPipeline,
                          KnowledgeComponent, ModelPaper)


class Command(BaseCommand):
    help = "Diagnose per-student pipeline health."

    def add_arguments(self, p):
        p.add_argument("--code", default=None)
        p.add_argument("--no-prompts", action="store_true")

    def handle(self, *args, **opts):
        qs = Student.objects.filter(is_active=True).order_by("code")
        if opts["code"]:
            qs = qs.filter(code=opts["code"])
        total = 0
        for s in qs:
            fs = self._check(s, not opts["no_prompts"])
            total += len(fs)
            tag = "OK" if not fs else str(len(fs)) + " issues"
            print("\n=== " + s.code + " " + s.name + " [" + tag + "] ===")
            for f in fs:
                print("  ! " + f)
            for p in TaskPipeline.objects.filter(owner_student=s).order_by("paper_code"):
                print("    pipe " + p.paper_code.ljust(12) + " stage=" + str(p.current_stage) + " " + p.status)
            live = StudentTask.objects.filter(student=s).exclude(status="SKIPPED")
            c = Counter(t.task_type for t in live)
            print("    live: " + str(dict(c)))
        print("\nTOTAL FINDINGS: " + str(total))
        return

    def _check(self, s, test_prompts):
        from exams.student_task_dispatch import PROMPT_SOURCES
        fs = []
        if not s.student_user_id:
            fs.append("no student_user")
        if not s.portal_token:
            fs.append("no portal_token")
        live = list(StudentTask.objects.filter(student=s).exclude(status="SKIPPED"))
        # A book pipeline is only required when the student HAS book tasks.
        # Standards: Rule 25; Rule 26; ISO/IEC/IEEE 29119-3 5.4.
        has_book = any(t.task_type == "BOOK_INGEST" for t in live)
        if has_book and not TaskPipeline.objects.filter(owner_student=s).exists():
            fs.append("no TaskPipeline row (student has BOOK_INGEST)")
        for t in live:
            ref = (t.task_ref or "").split("#")[0].strip()
            tt = t.task_type
            if tt in ("KC_MISCONCEPTION", "KC_SOCRATIC_LADDER"):
                if ref and not KnowledgeComponent.objects.filter(code=ref).exists():
                    fs.append("orphan " + tt + " ref=" + ref)
            elif tt in ("KC_TAG", "KC_DISCOVERY"):
                if ref and not ModelPaper.objects.filter(code=ref).exists():
                    fs.append("orphan " + tt + " ref=" + ref)
            if test_prompts and tt in PROMPT_SOURCES:
                fn = PROMPT_SOURCES[tt]
                try:
                    try:
                        out = fn(t, {})
                    except TypeError:
                        out = fn(t)
                    if out:
                        # Only real placeholder tokens; Urdu content may contain ___.
                        PLACEHOLDERS = (
                            "__KC_CODE__", "__WORDS__", "__PAPER_CODE__",
                            "__SUBJECT__", "__CODE__", "__CHAPTER__",
                            "__TITLE__", "__SOURCE_NOTE__", "__MEDIUM__",
                        )
                        for ph in PLACEHOLDERS:
                            if ph in out:
                                fs.append("unsub placeholder " + ph + " in " + tt)
                                break
                except Exception as e:
                    fs.append("prompt fail " + tt + "/" + ref[:25] + ": " + str(e)[:60])
        return fs
