"""Bulk-print MASTER_KC_MISCONCEPTION_PROMPT for every selected KC.

Usage:
    python manage.py bulk_kc_prompts [--out DIR] [--only-empty]
                                     [--codes CODE1 CODE2 ...]
                                     [--limit N] [--dry-run]

Writes <OUT>/<CODE>.txt for each selected KnowledgeComponent.
Reuses make_kc_prompt via call_command (Rule 10 - single canonical printer).

Standards: Rule 10 (one canonical path); Rule 11 (prompt is the printer
output, never paraphrased); ISO 9001:2015 7.5.3 (documented information);
ISO 21500:2021 4.3.3 (sequence - one printer, bulk driver).
"""
from io import StringIO
from pathlib import Path

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

from exams.models import KnowledgeComponent


DEFAULT_OUT = "/home/orkoworo/idealogy/tmp/kc_prompts"


class Command(BaseCommand):
    help = "Write MASTER_KC_MISCONCEPTION_PROMPT for each selected KC to <OUT>/<CODE>.txt."

    def add_arguments(self, parser):
        parser.add_argument("--out", type=str, default=DEFAULT_OUT,
                            help="Output directory (created if missing).")
        parser.add_argument("--only-empty", action="store_true",
                            help="Only KCs whose misconceptions list is empty.")
        parser.add_argument("--codes", nargs="*", default=None,
                            help="Explicit list of KC codes. Overrides --only-empty.")
        parser.add_argument("--limit", type=int, default=10,
                            help="Max ModelQuestion rows per prompt (passed to make_kc_prompt).")
        parser.add_argument("--dry-run", action="store_true",
                            help="Print what would be written; write nothing.")

    def handle(self, *args, **options):
        out_dir = Path(options["out"])
        only_empty = options["only_empty"]
        codes = options["codes"]
        limit = options["limit"]
        dry = options["dry_run"]

        if codes:
            qs = list(
                KnowledgeComponent.objects.filter(code__in=codes).order_by("code")
            )
            found = {k.code for k in qs}
            missing = set(codes) - found
            if missing:
                raise CommandError("Unknown KC codes: " + ", ".join(sorted(missing)))
        else:
            qs = list(KnowledgeComponent.objects.order_by("code"))
            if only_empty:
                qs = [k for k in qs if not (k.misconceptions or [])]

        if not qs:
            self.stdout.write("No KCs selected.")
            return

        if not dry:
            out_dir.mkdir(parents=True, exist_ok=True)

        written = 0
        skipped = 0
        for kc in qs:
            buf = StringIO()
            call_command("make_kc_prompt", kc.code, limit=limit, stdout=buf)
            text = buf.getvalue()
            if not text or "__KC_CODE__" in text:
                self.stdout.write(
                    "WARN " + kc.code + ": printer output looks malformed - skipped"
                )
                skipped += 1
                continue
            target = out_dir / (kc.code + ".txt")
            if dry:
                self.stdout.write(
                    "[dry] would write " + str(target) + " (" + str(len(text)) + " bytes)"
                )
            else:
                target.write_text(text, encoding="utf-8")
                self.stdout.write(
                    "wrote " + str(target) + " (" + str(len(text)) + " bytes)"
                )
                written += 1

        self.stdout.write(
            "--- total: " + str(written) + " written, " + str(skipped)
            + " skipped, out=" + str(out_dir)
        )
