"""kc_loop - one-command KC batch driver.

Combines batch prompt printing and JSON saving into a single call so the
teacher only needs one terminal command per batch:
    python manage.py kc_loop next --size 5
    ...paste into Claude/DeepSeek...
    python manage.py kc_loop save-and-next --size 5 <<'END'
    {AI JSON}
    END
    ...repeat...

Standards: Womack & Jones (muda reduction); ISO 21500:2021 4.3.3
(queue-driven sequence); Rule 10 (drivers only; make_kc_batch_prompt and
save_kc_batch_json remain canonical); Shift-Left Testing (5 KC/batch).
"""
import json
import sys
from io import StringIO
from pathlib import Path

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

from exams.models import KnowledgeComponent


GEN_DIR = Path("/home/orkoworo/idealogy/tmp/kc_generations")
REQUIRED = {"misconception", "level", "framework_ref", "mechanism",
            "faulty_reasoning", "incorrect_answer", "real_world_anchor",
            "next_step", "research_source", "confidence"}


def remaining_codes():
    have_json = {p.stem for p in GEN_DIR.glob("*.json")}
    out = []
    for kc in KnowledgeComponent.objects.order_by("code"):
        if (kc.misconceptions or []):
            continue
        if kc.code in have_json:
            continue
        out.append(kc.code)
    return out


def save_batch(obj):
    if not isinstance(obj, dict) or "batch" not in obj:
        raise SystemExit("missing top-level 'batch' key")
    entries = obj["batch"]
    if not isinstance(entries, list) or not entries:
        raise SystemExit("'batch' must be a non-empty list")
    saved = 0
    for e in entries:
        code = e.get("kc_code")
        cands = e.get("candidates")
        if not code or not isinstance(cands, list) or not cands:
            print("SKIP (missing kc_code or empty candidates):", code)
            continue
        for i, c in enumerate(cands, 1):
            miss = REQUIRED - set(c.keys())
            if miss:
                raise SystemExit(code + " candidate " + str(i)
                                 + " missing fields: " + ", ".join(sorted(miss)))
        GEN_DIR.mkdir(parents=True, exist_ok=True)
        out = GEN_DIR / (code + ".json")
        out.write_text(json.dumps({"candidates": cands}, indent=2,
                                  ensure_ascii=False), encoding="utf-8")
        print("saved " + str(out) + " (" + str(out.stat().st_size)
              + " bytes, " + str(len(cands)) + " candidates)")
        saved += 1
    return saved


class Command(BaseCommand):
    help = "KC loop: print next batch OR save JSON then print next batch."

    def add_arguments(self, parser):
        parser.add_argument("mode", choices=["status", "next", "save-and-next"])
        parser.add_argument("--size", type=int, default=5)

    def handle(self, *args, **options):
        mode = options["mode"]
        size = options["size"]

        if mode == "status":
            r = remaining_codes()
            self.stdout.write("remaining KCs: " + str(len(r)))
            for c in r:
                self.stdout.write("  " + c)
            return

        if mode == "save-and-next":
            raw = sys.stdin.read().strip()
            if not raw:
                raise SystemExit("no JSON on stdin")
            t = raw
            if t.startswith("```"):
                lines = t.splitlines()
                if lines and lines[0].startswith("```"):
                    lines = lines[1:]
                if lines and lines[-1].startswith("```"):
                    lines = lines[:-1]
                t = "\n".join(lines)
            try:
                obj = json.loads(t)
            except json.JSONDecodeError as e:
                raise SystemExit("INVALID JSON: " + str(e))
            save_batch(obj)
            self.stdout.write("")

        # fall through: print next batch
        rem = remaining_codes()
        if not rem:
            self.stdout.write("ALL KCS SAVED. Run: python manage.py bulk_ingest_kc_content")
            return
        batch = rem[:size]
        self.stdout.write("===== NEXT BATCH (" + str(len(batch)) + " KCs, "
                          + str(len(rem) - len(batch)) + " after this) =====")
        buf = StringIO()
        call_command("make_kc_batch_prompt", *batch, stdout=buf)
        self.stdout.write(buf.getvalue())
