"""make_term_readiness_prompt — print MASTER_TERM_READINESS_PROMPT.md
with KC metadata and linked ModelQuestion context substituted.

Usage:
    python manage.py make_term_readiness_prompt <kc_code>

Standards:
  Beck/McKeown/Kucan (three-tier vocabulary);
  Marzano Six-Step Process; Frayer Model; Hayden et al. 2019;
  Ausubel 1968 (advance organizers); Gagne 1971 (prerequisite analysis);
  AERA/APA/NCME 2014 Std 13.7; ISO 9001:2015 7.5.3;
  Rule H (Diagnostic Competence); Rule 10 (canonical path);
  Rule 11 (prompt mandatory).

Mirrors the pattern of make_kc_prompt.py (Rule 10).
"""
from pathlib import Path as _Path

from django.core.management.base import BaseCommand, CommandError

from exams.models import KnowledgeComponent, ModelPaper, ModelQuestion


PROMPT_PATH = _Path("/home/orkoworo/idealogy/prompts/MASTER_TERM_READINESS_PROMPT.md")


class Command(BaseCommand):
    help = "Print MASTER_TERM_READINESS_PROMPT.md with KC context substituted."

    def add_arguments(self, parser):
        parser.add_argument("kc_code", type=str,
                            help="KnowledgeComponent.code to print the prompt for.")

    def handle(self, *args, **options):
        kc_code = options["kc_code"]
        try:
            kc = KnowledgeComponent.objects.get(code=kc_code)
        except KnowledgeComponent.DoesNotExist:
            raise CommandError("KnowledgeComponent not found: " + kc_code)

        if not PROMPT_PATH.exists():
            raise CommandError("Prompt file missing: " + str(PROMPT_PATH))
        template = PROMPT_PATH.read_text(encoding="utf-8")

        # Find every ModelQuestion whose primary kc_code matches, OR whose
        # reasoning_chain.kc_tagging.secondary_kcs contains the code.
        primary = list(
            ModelQuestion.objects.filter(kc_code=kc_code).order_by("question_index")
        )
        secondary_hits = []
        for q in ModelQuestion.objects.exclude(reasoning_chain__isnull=True):
            rc = q.reasoning_chain if isinstance(q.reasoning_chain, dict) else {}
            tag = rc.get("kc_tagging") or {}
            if not isinstance(tag, dict):
                tag = {}
            sec = tag.get("secondary_kcs") or []
            if not isinstance(sec, list):
                sec = []
            if kc_code in sec and q not in primary:
                secondary_hits.append(q)

        context_qs = primary + secondary_hits
        context_qs.sort(key=lambda q: (q.paper_id or 0, q.question_index or 0))

        if not context_qs:
            self.stderr.write(
                "[stderr] no linked ModelQuestion rows for KC " + kc_code
                + " — prompt will be generated with an empty context block."
            )

        ctx_lines = []
        for q in context_qs:
            paper_code = q.paper.code if q.paper_id else "?"
            ma = (q.model_answer or "").strip().replace("\n", " ")
            if len(ma) > 260:
                ma = ma[:257] + "..."
            ctx_lines.append(
                f"Q{q.question_index} [{paper_code}] (marks={q.marks or '-'}, "
                f"newman={q.newman_focus or '-'}, chapter={q.chapter or '-'})\n"
                f"  Question: {q.question_text}\n"
                f"  Model answer: {ma}"
            )
        context_block = "\n\n".join(ctx_lines) if ctx_lines else "(no linked questions)"

        filled = (
            template
            .replace("__KC_CODE__", kc.code or "")
            .replace("__KC_TITLE__", kc.title or "")
            .replace("__SUBJECT__", kc.subject or "")
            .replace("__CHAPTER__", kc.chapter or "")
            .replace("__COGNITIVE_LEVEL__", kc.cognitive_level or "UND")
            .replace("__KC_DESCRIPTION__", kc.description or "(none)")
            .replace("__CONTEXT_QUESTIONS__", context_block)
        )

        self.stdout.write(filled)
        self.stderr.write(
            f"[stderr] filled for {kc.code}: {len(primary)} primary + "
            f"{len(secondary_hits)} secondary = {len(context_qs)} questions linked."
        )
