"""bulk_term_prompts — write one MASTER_TERM_READINESS_PROMPT per KC.

Usage:
    python manage.py bulk_term_prompts [--out-dir DIR]
                                       [--top N] [--codes C1 C2 ...]
                                       [--subject Chemistry] [--force]

Modes:
  Default (no --top, no --codes): every active KC of the subject.
  --top N     : the N KCs with the most linked ModelQuestions first.
  --codes ... : an explicit list of KC codes.

Output: one file per KC — <out-dir>/term_<KC_CODE>.txt

Does NOT call Gemini. Prints a manifest at the end so the teacher knows
how many Gemini calls to make and in what order.

Standards:
  Rule 10 (one canonical prompt printer per KC);
  Rule 11 (prompt is part of the instruction);
  ISO 21500:2021 4.3.3 (sequence — small batches reduce risk);
  Womack & Jones (Lean — smallest useful batch).
"""
import os
import re
from pathlib import Path

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

from exams.models import KnowledgeComponent, ModelQuestion


SAFE_CODE = re.compile(r"^[A-Z0-9\-]+$")


class Command(BaseCommand):
    help = "Write one MASTER_TERM_READINESS_PROMPT per KC to a directory."

    def add_arguments(self, parser):
        parser.add_argument("--out-dir", default="/tmp/term_prompts")
        parser.add_argument("--top", type=int, default=None,
                            help="Take the N KCs with most linked questions.")
        parser.add_argument("--codes", nargs="+", default=None,
                            help="Explicit KC codes to include.")
        parser.add_argument("--subject", default="Chemistry")
        parser.add_argument("--force", action="store_true",
                            help="Overwrite existing files.")

    def handle(self, *args, **opts):
        out_dir = Path(opts["out_dir"])
        out_dir.mkdir(parents=True, exist_ok=True)

        if opts["codes"]:
            kcs = list(KnowledgeComponent.objects.filter(
                code__in=opts["codes"]).order_by("code"))
            missing = set(opts["codes"]) - {k.code for k in kcs}
            if missing:
                raise CommandError("Unknown KC codes: " + ", ".join(sorted(missing)))
        else:
            kcs = list(KnowledgeComponent.objects.filter(
                subject=opts["subject"], is_active=True).order_by("code"))

        # Count linked ModelQuestions per KC (primary only — faster + sufficient)
        counts = {}
        for kc in kcs:
            counts[kc.code] = ModelQuestion.objects.filter(kc_code=kc.code).count()

        if opts["top"]:
            kcs.sort(key=lambda k: (-counts[k.code], k.code))
            kcs = kcs[:opts["top"]]

        written = []
        skipped = []
        for kc in kcs:
            if not SAFE_CODE.match(kc.code):
                skipped.append((kc.code, "unsafe code — skipped"))
                continue
            target = out_dir / f"term_{kc.code}.txt"
            if target.exists() and not opts["force"]:
                skipped.append((kc.code, f"exists (use --force): {target}"))
                continue
            from django.core.management import call_command
            from io import StringIO
            buf = StringIO()
            call_command("make_term_readiness_prompt", kc.code, stdout=buf, stderr=StringIO())
            target.write_text(buf.getvalue(), encoding="utf-8")
            written.append((kc.code, counts[kc.code], target, target.stat().st_size))

        self.stdout.write(f"out-dir: {out_dir}")
        self.stdout.write(f"written: {len(written)} | skipped: {len(skipped)}")
        for code, n, path, size in written:
            self.stdout.write(f"  {code:24s} q={n:3d}  {size:6d} B  {path.name}")
        for code, reason in skipped:
            self.stdout.write(self.style.WARNING(f"  SKIP {code}: {reason}"))

        if written:
            total = sum(n for _, n, _, _ in written)
            self.stdout.write(self.style.SUCCESS(
                f"manifest: {len(written)} prompts, {total} total linked questions."))
