"""batch_ingest_terms — split a batch Gemini reply and ingest each KC.

Usage:
    python manage.py batch_ingest_terms --file FILE [--source LABEL] [--strict]

Reads {"results": [{"kc_code": ..., "key_terms": [...]}, ...]}, splits it
into one temp file per KC, then calls ingest_terms for each.

Rule 10: ingest_terms remains the sole writer of KnowledgeComponent.key_terms.
This command only orchestrates.

Standards:
  Rule 9 (append-only, never overwrite);
  Rule 10 (one canonical writer);
  Rule 11 (prompt file exists);
  ISO 9001:2015 7.5.3 (documented information);
  PMBOK 7th ed. 6.4 (batch orchestration).
"""
import json
from pathlib import Path as _Path

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

from exams.parsing import extract_json


class Command(BaseCommand):
    help = "Split a batch Gemini reply and ingest each KC via ingest_terms."

    def add_arguments(self, parser):
        parser.add_argument("--file", required=True, type=str,
                            help="Batch JSON file: {results:[{kc_code,key_terms},...]}.")
        parser.add_argument("--source", default="", type=str)
        parser.add_argument("--strict", action="store_true")
        parser.add_argument("--dry-run", action="store_true")
        parser.add_argument("--tmp-dir", default="/tmp", type=str)

    def handle(self, *args, **opts):
        path = _Path(opts["file"])
        if not path.exists():
            raise CommandError("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))

        results = data.get("results")
        if not isinstance(results, list) or not results:
            raise CommandError("Expected top-level 'results' list.")

        source_label = opts["source"] or path.name
        tmp_dir = _Path(opts["tmp_dir"])
        tmp_dir.mkdir(parents=True, exist_ok=True)

        seen = set()
        ok = 0
        failed = 0

        for i, entry in enumerate(results, start=1):
            code = (entry.get("kc_code") or "").strip()
            terms = entry.get("key_terms") or []
            if not code:
                self.stderr.write(f"WARN result {i}: missing kc_code, skipped")
                failed += 1
                continue
            if code in seen:
                self.stderr.write(f"WARN result {i}: duplicate kc_code {code}, skipped")
                failed += 1
                continue
            seen.add(code)

            per_kc = tmp_dir / f"terms_{code}.json"
            with per_kc.open("w", encoding="utf-8") as f:
                json.dump({"key_terms": terms}, f, indent=2, ensure_ascii=False)

            argv = ["ingest_terms", code, "--terms-file", str(per_kc),
                    "--source", source_label]
            if opts["strict"]:
                argv.append("--strict")
            if opts["dry_run"]:
                argv.append("--dry-run")
            try:
                call_command(*argv)
                ok += 1
            except Exception as exc:
                self.stderr.write(f"FAIL {code}: {exc}")
                failed += 1

        self.stdout.write(self.style.SUCCESS(
            f"batch done: {ok} KC(s) ingested, {failed} failed, "
            f"per-KC files written under {tmp_dir}/terms_<CODE>.json"
        ))
