"""bulk_kc_suggest - propose Knowledge Component tags for a subject bank.

Modes (pick exactly one):

  --print-prompt       Print one chunk of the filled Gemini prompt.
  --print-all-chunks   Write every chunk as a separate file for Gemini.
  --file F [F ...]     Validate one or more Gemini JSON responses; merge to CSV.

Does NOT write to the DB. kc_tag remains the sole writer (Rule 10).

Standards:
  Tatsuoka 1983 (Rule Space, Q-matrix attributes);
  Templin & Hoffman 2013 (expert judgment primary for attribute definition);
  de la Torre & Chiu 2016 (multi-attribute diagnostic classification);
  AERA/APA/NCME 2014 Std 13.7 (every value names its construct);
  ISO 9001:2015 7.5.3 (documented information);
  ISO 21500:2021 4.3.3 (sequence - decompose large work);
  PMBOK 7th ed. 6.4 (chunk size fits tool constraints);
  Rule H (Diagnostic Competence); Rule 10 (one canonical writer);
  Rule 11 (Prompt Mandatory).
"""
import csv
from pathlib import Path

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

from exams.models import ModelPaper, ModelQuestion, KnowledgeComponent
from exams.parsing import extract_json


PROMPT_PATH = Path("/home/orkoworo/idealogy/prompts/MASTER_KC_TAG_PROMPT.md")
MAX_KCS_PER_QUESTION = 3
DEFAULT_CHUNK_SIZE = 40


class Command(BaseCommand):
    help = "Suggest KC tags for a subject bank (chunked prompt OR merge responses)."

    def add_arguments(self, parser):
        parser.add_argument("--bank", required=True)
        parser.add_argument("--class-level", type=int, default=9)
        parser.add_argument("--chunk-size", type=int, default=DEFAULT_CHUNK_SIZE)
        parser.add_argument("--chunk", type=int, default=1)
        parser.add_argument("--start-idx", type=int, default=None,
                            help="Only consider questions with question_index >= this value.")
        parser.add_argument("--print-prompt", action="store_true")
        parser.add_argument("--print-all-chunks", action="store_true")
        parser.add_argument("--out-dir", default="/tmp/kc_prompts")
        parser.add_argument("--file", nargs="+")
        parser.add_argument("--out-csv", default="/tmp/qmatrix_review.csv")

    def handle(self, *args, **opts):
        modes = [bool(opts["print_prompt"]), bool(opts["print_all_chunks"]), bool(opts["file"])]
        if sum(modes) != 1:
            raise CommandError("Pick exactly one mode: --print-prompt, --print-all-chunks, or --file.")
        if opts["chunk_size"] < 1:
            raise CommandError("--chunk-size must be >= 1")

        bank_code = opts["bank"].upper()
        paper = ModelPaper.objects.filter(code=bank_code).first()
        if paper is None:
            raise CommandError(f"subject bank not found: {bank_code}")

        questions = list(ModelQuestion.objects.filter(paper=paper).order_by("question_index"))
        if opts.get("start_idx") is not None:
            questions = [q for q in questions if q.question_index >= opts["start_idx"]]
        if not questions:
            raise CommandError(f"no questions in bank {bank_code} at or after start-idx")

        subject = paper.subject or ""
        kcs = list(KnowledgeComponent.objects.filter(subject=subject, is_active=True).order_by("code"))
        if not kcs:
            raise CommandError(f"no active KnowledgeComponent rows for subject {subject!r}")

        size = opts["chunk_size"]
        total = (len(questions) + size - 1) // size

        if opts["print_prompt"]:
            return self._print_one_chunk(subject, opts["class_level"], kcs, questions,
                                         opts["chunk"], total, size)
        if opts["print_all_chunks"]:
            return self._print_all_chunks(subject, opts["class_level"], kcs, questions,
                                          size, total, Path(opts["out_dir"]))
        return self._merge_and_validate([Path(p) for p in opts["file"]],
                                        Path(opts["out_csv"]), kcs, questions, bank_code)

    def _fill_template(self, subject, class_level, kcs, chunk_questions, chunk_note):
        if not PROMPT_PATH.exists():
            raise CommandError(f"prompt file missing: {PROMPT_PATH}")
        template = PROMPT_PATH.read_text(encoding="utf-8")
        kc_lines = "\n".join(f"- `{kc.code}` - {kc.title}" for kc in kcs)
        q_lines = "\n".join(f"{q.question_index}. {q.question_text}" for q in chunk_questions)
        header = f"**{chunk_note}**\n\n" if chunk_note else ""
        return header + (
            template
            .replace("__SUBJECT__", subject)
            .replace("__CLASS__", str(class_level))
            .replace("__KC_COUNT__", str(len(kcs)))
            .replace("__KC_LIST__", kc_lines)
            .replace("__Q_COUNT__", str(len(chunk_questions)))
            .replace("__QUESTIONS__", q_lines)
        )

    def _print_one_chunk(self, subject, class_level, kcs, questions, chunk, total, size):
        if chunk < 1 or chunk > total:
            raise CommandError(f"--chunk must be between 1 and {total}")
        start = (chunk - 1) * size
        chunk_qs = questions[start:start + size]
        note = f"Chunk {chunk} of {total} - tag only the {len(chunk_qs)} questions listed below."
        self.stdout.write(self._fill_template(subject, class_level, kcs, chunk_qs, note))
        self.stderr.write(f"[stderr] emitted chunk {chunk}/{total}: {len(chunk_qs)} questions.")

    def _print_all_chunks(self, subject, class_level, kcs, questions, size, total, out_dir):
        out_dir.mkdir(parents=True, exist_ok=True)
        for i in range(total):
            start = i * size
            chunk_qs = questions[start:start + size]
            note = f"Chunk {i + 1} of {total} - tag only the {len(chunk_qs)} questions listed below."
            text = self._fill_template(subject, class_level, kcs, chunk_qs, note)
            path = out_dir / f"prompt_{i + 1:02d}.txt"
            path.write_text(text, encoding="utf-8")
            self.stdout.write(f"wrote {path} ({path.stat().st_size} bytes) - {len(chunk_qs)} questions")

    def _merge_and_validate(self, paths, out_csv, kcs, questions, bank_code):
        for p in paths:
            if not p.exists():
                raise CommandError(f"response file not found: {p}")

        approved = {kc.code for kc in kcs}
        by_index = {q.question_index: q for q in questions}

        tags_by_index = {}
        dup_across = []
        parse_errors = []

        for p in paths:
            try:
                data = extract_json(p.read_text(encoding="utf-8"))
            except ValueError as e:
                parse_errors.append(f"{p.name}: {e}")
                continue
            for t in (data.get("tags") or []):
                idx = t.get("question_index")
                if idx in tags_by_index:
                    dup_across.append(f"q_idx {idx} duplicated (in {p.name})")
                    continue
                tags_by_index[idx] = (t, p.name)

        missing = sorted(set(by_index) - set(tags_by_index))
        unknown = sorted(set(tags_by_index) - set(by_index))

        rows = []
        row_error_count = 0
        for idx in sorted(by_index):
            if idx not in tags_by_index:
                continue
            t, src = tags_by_index[idx]
            primary = t.get("primary_kc") or ""
            secondary = t.get("secondary_kcs") or []
            if not isinstance(secondary, list):
                secondary = []
            row_errors = []
            if primary not in approved:
                row_errors.append(f"primary {primary!r} not approved")
            for s in secondary:
                if s not in approved:
                    row_errors.append(f"secondary {s!r} not approved")
            if 1 + len(secondary) > MAX_KCS_PER_QUESTION:
                row_errors.append(f"{1 + len(secondary)} KCs (max {MAX_KCS_PER_QUESTION})")
            try:
                conf = float(t.get("confidence", 0.0))
            except (TypeError, ValueError):
                conf = 0.0
            status = "OK" if not row_errors else "ERR"
            if row_errors:
                row_error_count += 1
            rows.append({
                "question_index": idx,
                "question_text": by_index[idx].question_text[:120].replace("\n", " "),
                "primary_kc": primary,
                "secondary_kcs": ";".join(secondary),
                "confidence": f"{conf:.2f}",
                "reasoning": (t.get("reasoning") or "")[:200].replace("\n", " "),
                "row_status": status,
                "row_errors": "; ".join(row_errors),
                "source_file": src,
            })

        out_csv.parent.mkdir(parents=True, exist_ok=True)
        with out_csv.open("w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=[
                "question_index", "question_text", "primary_kc",
                "secondary_kcs", "confidence", "reasoning",
                "row_status", "row_errors", "source_file",
            ])
            writer.writeheader()
            writer.writerows(rows)

        self.stdout.write(f"wrote {out_csv} ({out_csv.stat().st_size} bytes)")
        self.stdout.write(
            f"bank: {bank_code} | files: {len(paths)} | "
            f"questions: {len(questions)} | tagged: {len(rows)} | "
            f"missing: {len(missing)} | unknown: {len(unknown)} | "
            f"dups: {len(dup_across)} | row errors: {row_error_count} | "
            f"parse errors: {len(parse_errors)}"
        )
        for label, items in (("parse", parse_errors), ("dup", dup_across),
                             ("unknown", unknown), ("missing", missing)):
            for x in items[:10]:
                self.stdout.write(f"  ! {label}: {x}")

        if missing or unknown or dup_across or row_error_count or parse_errors:
            self.stdout.write("Fix errors above before running kc_tag.")
        else:
            self.stdout.write("All responses valid. Review the CSV, then run kc_tag.")
