"""ingest_terms — write key_terms on a KnowledgeComponent from a JSON file.

Usage:
    python manage.py ingest_terms <kc_code> --terms-file FILE
                        [--dry-run] [--strict] [--replace] [--source LABEL]

The JSON file must contain the output of MASTER_TERM_READINESS_PROMPT.md:
    {"key_terms": [
        {"term": "...", "roman_urdu": "...", "definition": "...",
         "example": "...", "non_example": "...",
         "probes": {"receptive": "...", "discrimination": "...", "productive": "..."},
         "confidence": 0.95}, ...]}

Behaviour:
  - Validates each term has all required fields (Rule 11 compliance).
  - By default MERGES into the KC's existing key_terms list, skipping
    any term whose `term` string already exists (append-only, Rule 9).
  - --replace clears the existing list first (explicit destructive flag).
  - Each stored entry adds tagged_by + tagged_at + source_file (ALCOA+).

Standards:
  Beck/McKeown/Kucan (three-tier vocabulary);
  Marzano Six-Step Process; Frayer Model;
  Hayden et al. 2019 (receptive + productive vocabulary assessment);
  Ausubel 1968; Gagne 1971; Bloom Revised / Anderson & Krathwohl 2001;
  AERA/APA/NCME 2014 Std 13.7 (each stored value names its construct);
  ISO 9001:2015 7.5.3 (JSON file is documented evidence);
  Rule 9 (append-only; never silently overwrite);
  Rule 10 (one canonical writer for key_terms);
  Rule 11 (prompt file exists at ~/idealogy/prompts/MASTER_TERM_READINESS_PROMPT.md).
"""
from datetime import datetime, timezone
from pathlib import Path as _Path

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

import re as _re

from exams.models import KnowledgeComponent
from exams.parsing import extract_json


REQUIRED_PROBES = ("receptive", "discrimination", "productive")
REQUIRED_FIELDS = ("term", "roman_urdu", "definition", "example",
                   "non_example", "probes", "confidence")

# Turn 3 (2026-10-11) - V-checks.
# Standards: Rule 8 (no Urdu script); Beck/McKeown/Kucan three-tier
# vocabulary; Marzano Six-Step; Frayer Model; Hayden et al. 2019;
# ISO 24495-1:2023 (plain language).
MIN_TERM_LEN = 2
MAX_TERM_LEN = 40
MIN_DEF_LEN = 20
MIN_EXAMPLE_LEN = 5

_URDU_RANGES = [(0x0600, 0x06FF), (0x0750, 0x077F),
                (0xFB50, 0xFDFF), (0xFE70, 0xFEFF)]
URDU_RE = _re.compile(
    "[" + "".join(chr(lo) + "-" + chr(hi) for lo, hi in _URDU_RANGES) + "]"
)


def _has_urdu_script(s):
    """Rule 8 enforcement. Returns True if any Urdu/Arabic script char present."""
    return bool(URDU_RE.search(str(s or "")))


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


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


def _validate_term(t, i):
    """Return (ok, entry, errors) — entry has tagged_by/at/source added later."""
    errors = []
    missing = [f for f in REQUIRED_FIELDS if f not in t or t.get(f) in (None, "")]
    if missing:
        errors.append(f"missing field(s): {', '.join(missing)}")
        return False, None, errors

    probes = t.get("probes") or {}
    if not isinstance(probes, dict):
        errors.append("probes is not a dict")
        return False, None, errors
    for key in REQUIRED_PROBES:
        if not _clean(probes.get(key)):
            errors.append(f"missing probe: {key}")

    conf = _float(t.get("confidence"))
    if conf is None or not (0.0 <= conf <= 1.0):
        errors.append(f"confidence out of range or invalid: {t.get('confidence')!r}")

    # --- V-checks (Turn 3, 2026-10-11) ---
    _term = _clean(t.get("term"))
    if not (MIN_TERM_LEN <= len(_term) <= MAX_TERM_LEN):
        errors.append(f"V1 term length {len(_term)} out of range "
                      f"({MIN_TERM_LEN}-{MAX_TERM_LEN})")

    _defn = _clean(t.get("definition"))
    if len(_defn) < MIN_DEF_LEN:
        errors.append(f"V2 definition too short ({len(_defn)} < {MIN_DEF_LEN})")

    _exmp = _clean(t.get("example"))
    if len(_exmp) < MIN_EXAMPLE_LEN:
        errors.append(f"V2 example too short ({len(_exmp)} < {MIN_EXAMPLE_LEN})")

    for fname in ("term", "roman_urdu", "definition", "example", "non_example"):
        if _has_urdu_script(t.get(fname)):
            errors.append(f"V7 Urdu script in field {fname!r} (Rule 8)")
    for pk in REQUIRED_PROBES:
        if _has_urdu_script(probes.get(pk)):
            errors.append(f"V7 Urdu script in probe {pk!r} (Rule 8)")

    if errors:
        return False, None, errors

    entry = {
        "term": _clean(t["term"]),
        "roman_urdu": _clean(t["roman_urdu"]),
        "definition": _clean(t["definition"]),
        "example": _clean(t["example"]),
        "non_example": _clean(t["non_example"]),
        "probes": {k: _clean(probes[k]) for k in REQUIRED_PROBES},
        "confidence": conf,
    }
    return True, entry, []


class Command(BaseCommand):
    help = "Write key_terms on a KnowledgeComponent from a JSON file."

    def add_arguments(self, parser):
        parser.add_argument("kc_code", type=str,
                            help="KnowledgeComponent.code to write terms for.")
        parser.add_argument("--terms-file", required=True, type=str,
                            help="Path to JSON file with {\"key_terms\": [...]}.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Validate and report; write nothing.")
        parser.add_argument("--strict", action="store_true",
                            help="Abort on first invalid term.")
        parser.add_argument("--replace", action="store_true",
                            help="Clear existing key_terms before writing (destructive).")
        parser.add_argument("--source", type=str, default="",
                            help="Provenance label (defaults to input filename).")

    def handle(self, *args, **options):
        kc_code = options["kc_code"]
        path = _Path(options["terms_file"])
        dry_run = options["dry_run"]
        strict = options["strict"]
        replace = options["replace"]
        source_label = options["source"] or path.name

        try:
            kc = KnowledgeComponent.objects.get(code=kc_code)
        except KnowledgeComponent.DoesNotExist:
            raise CommandError("KnowledgeComponent not found: " + kc_code)

        if not path.exists():
            raise CommandError("Terms file not found: " + str(path))

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

        raw_terms = data.get("key_terms") or []
        if not isinstance(raw_terms, list):
            raise CommandError("'key_terms' must be a list.")

        existing = list(kc.key_terms or [])
        existing_term_strings = {e.get("term") for e in existing if isinstance(e, dict)}

        now = datetime.now(timezone.utc).isoformat()
        new_entries = []
        warnings = 0
        skipped_dupes = 0

        for i, t in enumerate(raw_terms, start=1):
            ok, entry, errs = _validate_term(t, i)
            if not ok:
                for e in errs:
                    self.stderr.write(f"WARN term {i}: {e}")
                warnings += 1
                if strict:
                    raise CommandError(f"Strict: term {i} invalid: {'; '.join(errs)}")
                continue

            if entry["term"] in existing_term_strings:
                skipped_dupes += 1
                self.stderr.write(f"SKIP term {i}: already present — {entry['term']!r}")
                continue

            entry["tagged_by"] = "gemini:term_readiness"
            entry["tagged_at"] = now
            entry["source_file"] = source_label
            new_entries.append(entry)
            existing_term_strings.add(entry["term"])

        if not new_entries and not skipped_dupes:
            raise CommandError("No valid terms to write.")

        merged = list(existing)
        if replace:
            merged = []
        merged.extend(new_entries)

        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN - nothing written."))
            self.stdout.write(f"KC: {kc.code}")
            self.stdout.write(f"Existing terms: {len(existing)}")
            self.stdout.write(f"New valid terms: {len(new_entries)}")
            self.stdout.write(f"Skipped dupes: {skipped_dupes} | Warnings: {warnings}")
            self.stdout.write(f"Would write total: {len(merged)} (replace={replace})")
            return

        with transaction.atomic():
            kc.key_terms = merged
            kc.save(update_fields=["key_terms"])

        self.stdout.write(self.style.SUCCESS(
            f"Wrote {len(new_entries)} new term(s) to {kc.code} "
            f"(total now {len(merged)}). Warnings: {warnings}"
        ))
        if kc.key_terms:
            self.stdout.write(f"Sample: {kc.key_terms[0].get('term')!r} "
                              f"| probes keys: {list(kc.key_terms[0].get('probes', {}).keys())}")
