"""Set kc_code on ModelQuestion rows from a Q-matrix JSON file.

Usage:
    python manage.py kc_tag <json_file> [--bank CODE] [--dry-run] [--strict]

Two tag shapes (backwards compatible):
  LEGACY:  {"paper_code": "...", "question_index": N, "kc_code": "..."}
  FULL:    {"question_index": N, "primary_kc": "...",
            "secondary_kcs": [...], "confidence": 0.95, "reasoning": "..."}

If --bank CODE is given, all tags target that ModelPaper and per-tag
paper_code is ignored.

Extended fields (secondary_kcs, confidence, reasoning) are stored inside
ModelQuestion.reasoning_chain under the "kc_tagging" namespace, merged
with any existing keys (ALCOA+ / Rule 9: never overwrite existing data).

Standards:
  Tatsuoka 1983 (Rule Space; Q-matrix attributes);
  Buck et al. 1998; de la Torre & Chiu 2016; Templin & Hoffman 2013
    (multi-attribute Q-matrix; expert judgment primary);
  arXiv 2604.16398 (2026) (LLM candidate tags, expert oversight);
  AERA/APA/NCME 2014 Std 13.7 (every stored kc_code names its KC);
  ISO 9001:2015 7.5.3 (JSON file is documented evidence);
  Django docs (custom command conventions);
  Rule 9 (append-only; never overwrite existing data);
  Rule 10 (one canonical writer per feature);
  Rule 11 (prompt file for AI-drafted tags exists).
"""
from datetime import datetime, timezone
from pathlib import Path as _Path

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

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


def _clean(value, default=""):
    if value is None:
        return default
    return str(value).strip()


def _int(value):
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _float(value):
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


class Command(BaseCommand):
    help = "Set kc_code on ModelQuestion rows from a Q-matrix JSON file."

    def add_arguments(self, parser):
        parser.add_argument("json_file", type=str,
                            help="Path to JSON file with the Q-matrix tags.")
        parser.add_argument("--bank", type=str, default=None,
                            help="Subject-bank code; all tags target this ModelPaper.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Validate and report; write nothing.")
        parser.add_argument("--strict", action="store_true",
                            help="Abort on any unknown paper, question, or KC.")
        parser.add_argument("--source", type=str, default="",
                            help="Provenance label (defaults to input filename).")

    def handle(self, *args, **options):
        path = options["json_file"]
        dry_run = options["dry_run"]
        strict = options["strict"]
        bank_code = (options.get("bank") or "").upper() or None
        source_label = options.get("source") or _Path(path).name

        try:
            raw = _Path(path).read_text(encoding="utf-8")
        except FileNotFoundError:
            raise CommandError("File not found: " + path)
        try:
            data = extract_json(raw)
        except ValueError as exc:
            raise CommandError("Invalid JSON: " + str(exc))

        if isinstance(data, list): data = {"tags": data}
        tags = data.get("tags") or []
        if not tags:
            raise CommandError("No tags entries in input.")

        papers = {p.code: p for p in ModelPaper.objects.all()}
        kc_subjects = dict(KnowledgeComponent.objects.values_list("code", "subject"))
        kc_codes = set(kc_subjects.keys())

        if bank_code and bank_code not in papers:
            raise CommandError("Unknown --bank code: " + bank_code)

        valid = []
        warnings = 0

        for i, t in enumerate(tags, start=1):
            if bank_code:
                paper_code = bank_code
            else:
                paper_code = _clean(t.get("paper_code"))

            qi = _int(t.get("question_index"))
            # Postel's Robustness Principle (RFC 761): accept aliases.
            # Some LLM outputs use {"kc_codes": ["X","Y"]} instead of
            # {"primary_kc": "X", "secondary_kcs": ["Y"]}. Both mean the
            # same thing. First item = primary, rest = secondary.
            # Standards: RFC 761; NIST SP 800-53 SI-10; Rule 4.
            primary = _clean(t.get("primary_kc")) or _clean(t.get("kc_code"))
            secondary = t.get("secondary_kcs") or []
            if not primary and isinstance(t.get("kc_codes"), list):
                _kc_list = [_clean(x) for x in t["kc_codes"] if _clean(x)]
                if _kc_list:
                    primary = _kc_list[0]
                    secondary = _kc_list[1:]
            secondary = t.get("secondary_kcs") or []
            if not isinstance(secondary, list):
                secondary = []
            secondary = [s for s in (_clean(s) for s in secondary) if s]
            confidence = _float(t.get("confidence"))
            reasoning = _clean(t.get("reasoning"))

            if not paper_code or qi is None:
                self.stderr.write("WARN tag " + str(i)
                                  + ": missing paper_code/question_index, skipped")
                warnings += 1
                if strict:
                    raise CommandError("Strict: tag " + str(i) + " incomplete.")
                continue

            if paper_code not in papers:
                self.stderr.write("WARN tag " + str(i) + ": unknown paper " + paper_code)
                warnings += 1
                if strict:
                    raise CommandError("Strict: unknown paper " + paper_code)
                continue

            paper = papers[paper_code]
            try:
                q = ModelQuestion.objects.get(paper=paper, question_index=qi)
            except ModelQuestion.DoesNotExist:
                self.stderr.write("WARN tag " + str(i) + ": no ModelQuestion "
                                  + paper_code + " Q" + str(qi))
                warnings += 1
                if strict:
                    raise CommandError("Strict: no ModelQuestion "
                                       + paper_code + " Q" + str(qi))
                continue

            if not primary:
                self.stderr.write("WARN tag " + str(i) + ": empty primary KC, skipped")
                warnings += 1
                if strict:
                    raise CommandError("Strict: empty primary KC on tag " + str(i))
                continue

            if primary not in kc_codes:
                self.stderr.write("WARN tag " + str(i) + ": unknown primary KC "
                                  + primary)
                warnings += 1
                if strict:
                    raise CommandError("Strict: unknown KC " + primary)
                continue

            # Cross-subject guard (NIST SP 800-53 SI-10; AERA Std 1.0;
            # Rule 26). A paper and its KC must share the same subject.
            paper_subj = (getattr(paper, "subject", "") or "").strip().lower()
            kc_subj_p = (kc_subjects.get(primary) or "").strip().lower()
            if paper_subj and kc_subj_p and paper_subj != kc_subj_p:
                self.stderr.write(
                    "WARN tag " + str(i) + ": subject mismatch paper "
                    + paper_code + " (" + paper_subj + ") vs KC "
                    + primary + " (" + kc_subj_p + ")"
                )
                warnings += 1
                if strict:
                    raise CommandError(
                        "Strict: subject mismatch " + paper_code + "/" + primary)
                continue

            # Filter secondary KCs by existence AND same-subject rule.
            bad_secondary = [
                s for s in secondary
                if (s not in kc_codes)
                or (paper_subj and (kc_subjects.get(s) or "").strip().lower()
                    and (kc_subjects.get(s) or "").strip().lower() != paper_subj)
            ]
            if bad_secondary:
                self.stderr.write("WARN tag " + str(i) + ": unknown secondary KC(s): "
                                  + ", ".join(bad_secondary))
                warnings += 1
                if strict:
                    raise CommandError("Strict: unknown secondary KC(s): "
                                       + ", ".join(bad_secondary))
                secondary = [
                    s for s in secondary
                    if (s in kc_codes)
                    and (not paper_subj
                         or (kc_subjects.get(s) or "").strip().lower() == paper_subj)
                ]

            if len(secondary) > 2:
                secondary = secondary[:2]

            valid.append((q, primary, secondary, confidence, reasoning))

        if not valid:
            raise CommandError("No valid tags to apply.")

        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN - nothing written."))
            self.stdout.write("Would tag " + str(len(valid)) + " question(s).")
            self.stdout.write("Warnings: " + str(warnings))
            return

        now = datetime.now(timezone.utc).isoformat()
        with transaction.atomic():
            for q, primary, secondary, confidence, reasoning in valid:
                q.kc_code = primary
                rc = dict(q.reasoning_chain or {})
                rc["kc_tagging"] = {
                    "primary_kc": primary,
                    "secondary_kcs": secondary,
                    "confidence": confidence,
                    "reasoning": reasoning,
                    "tagged_by": "gemini:kc_tagger_gem",
                    "tagged_at": now,
                    "source_file": source_label,
                }
                q.reasoning_chain = rc
                q.save(update_fields=["kc_code", "reasoning_chain"])

        empty = ModelQuestion.objects.filter(kc_code="").count()
        total = ModelQuestion.objects.count()
        tagged = total - empty

        self.stdout.write(self.style.SUCCESS(
            "Tagged " + str(len(valid)) + " question(s) with extended data. "
            "Warnings: " + str(warnings)))

        self.stdout.write(
            "G3 gate: " + str(tagged) + "/" + str(total)
            + " ModelQuestion rows have a kc_code. Empty slots: " + str(empty))
        if empty > 0:
            self.stdout.write(self.style.WARNING(
                "G3 PASS requires zero empty slots. Not yet passed."))
        else:
            self.stdout.write(self.style.SUCCESS("G3 gate PASSED."))
