"""batch_term_prompts — print ONE prompt covering multiple KCs at once.

Usage:
    python manage.py batch_term_prompts CODE1 CODE2 [CODE3 ...]
                                       [--out FILE]

Reads MASTER_TERM_READINESS_PROMPT.md, substitutes per-KC blocks for
each code, and writes a single combined prompt. Gemini replies with:
    {"results": [{"kc_code": "...", "key_terms": [...]}, ...]}

Standards:
  Rule 11 (prompt mandatory); Rule 10 (canonical printer);
  PMBOK 7th ed. 6.4 (batch size fits tool constraint — 3 KCs ≈ 5K
    output tokens, safely under Gemini's 8K cap);
  ISO 21500:2021 4.3.3 (sequence — smaller batches = less rework);
  Womack & Jones (Lean — batch right-sized).
"""
from pathlib import Path as _Path
from io import StringIO

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

from exams.models import KnowledgeComponent, ModelQuestion


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


class Command(BaseCommand):
    help = "Print ONE combined term-readiness prompt for multiple KCs."

    def add_arguments(self, parser):
        parser.add_argument("kc_codes", nargs="+", type=str)
        parser.add_argument("--out", default=None,
                            help="Optional output file (default: stdout).")

    def handle(self, *args, **opts):
        codes = opts["kc_codes"]
        if len(codes) < 1:
            raise CommandError("Provide at least one KC code.")
        if len(codes) > 8:
            raise CommandError(
                "Max 8 KCs per batch (Rule 10 + PMBOK 6.4; keeps Gemini output under 8K tokens).")

        header = (
            "# MASTER TERM READINESS PROMPT — BATCH MODE\n"
            f"**Batch size:** {len(codes)} KnowledgeComponents\n"
            "**Purpose:** For EACH KC below, generate 3–10 Tier-3 key terms.\n"
            "**Standards:** Beck/McKeown/Kucan; Marzano Six-Step; Frayer Model; "
            "Hayden et al. 2019; Gagné 1971; Bloom Revised; AERA/APA/NCME 2014 Std 13.7; "
            "Rule H (Diagnostic Competence); Rule 11 (Prompt Mandatory).\n\n"
            "---\n\n"
            "## ROLE\n"
            "You are an expert Chemistry teacher for 9th-class BISE Gujranwala in Pakistan. "
            "Students often fail because they do not know the Tier-3 key terms. Your task: "
            "surface those terms per KC and write them for a struggling student.\n\n"
            "## WHAT IS A TIER-3 KEY TERM?\n"
            "Domain-specific, low-frequency, single-meaning in context, not inferable from "
            "surrounding words. Examples: carbon monoxide, hemoglobin, stoichiometry, covalent bond. "
            "NOT key terms: air, water, burn, plant.\n\n"
        )

        per_kc_blocks = []
        for i, code in enumerate(codes, start=1):
            try:
                kc = KnowledgeComponent.objects.get(code=code)
            except KnowledgeComponent.DoesNotExist:
                raise CommandError("KC not found: " + code)

            buf = StringIO()
            call_command("make_term_readiness_prompt", code,
                         stdout=buf, stderr=StringIO())
            full = buf.getvalue()

            # Extract only the KC metadata + context block from the single-KC prompt
            start = full.find("## KNOWLEDGE COMPONENT")
            end = full.find("## OUTPUT (STRICT JSON")
            if start < 0 or end < 0:
                raise CommandError("Unexpected prompt layout for " + code)
            body = full[start:end].rstrip()

            per_kc_blocks.append(f"### KC {i}: {code}\n{body}\n")

        schema = (
            "## OUTPUT (STRICT JSON — no prose, no markdown fences)\n"
            "Return ONLY one JSON object covering every KC in this batch:\n\n"
            "{\n"
            '  "results": [\n'
            "    {\n"
            '      "kc_code": "<one of the KC codes below>",\n'
            '      "key_terms": [\n'
            "        {\n"
            '          "term": "...", "roman_urdu": "...",\n'
            '          "definition": "...", "example": "...", "non_example": "...",\n'
            '          "probes": {"receptive": "...", "discrimination": "...", "productive": "..."},\n'
            '          "confidence": 0.9\n'
            "        }\n"
            "      ]\n"
            "    }\n"
            "  ]\n"
            "}\n\n"
            "## RULES (MANDATORY)\n"
            "1. One result object per KC in the batch — every kc_code MUST appear exactly once.\n"
            "2. Per KC: 3–10 Tier-3 terms. Fewer is better than padded guesses.\n"
            "3. Every term must be traceable to that KC's linked context questions.\n"
            "4. definition, example, non_example, and all 3 probes in **Roman Urdu, Latin letters only**.\n"
            "5. non_example must name a term the student is likely to confuse (CO vs CO2, ionic vs covalent).\n"
            "6. Three probes per term: receptive (define), discrimination (tell apart), productive (use).\n"
            "7. confidence is float 0.0–1.0.\n"
            "8. Output valid JSON only. No prose, no fences.\n\n"
            "## Begin\n"
            "Generate key_terms for every KC below. Output the JSON object only.\n"
        )

        combined = (
            header
            + "## KNOWLEDGE COMPONENTS IN THIS BATCH\n\n"
            + "\n".join(per_kc_blocks)
            + "\n---\n\n"
            + schema
        )

        if opts["out"]:
            p = _Path(opts["out"])
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(combined, encoding="utf-8")
            self.stdout.write(f"wrote {p} ({p.stat().st_size} bytes) for {len(codes)} KCs: "
                              + ", ".join(codes))
        else:
            self.stdout.write(combined)
            self.stderr.write(f"[stderr] batch of {len(codes)} KCs: " + ", ".join(codes))
