"""Bulk-ingest KC misconception JSONs into their KnowledgeComponents.

Usage:
    python manage.py bulk_ingest_kc_content [--dir DIR] [--dry-run]
                                            [--strict] [--skip-existing]

Reads every *.json in DIR (default ~/idealogy/tmp/kc_generations/) and
calls generate_kc_content for each. Filename (minus .json) is the KC code.
Per-file failure is isolated: a bad JSON logs a WARN and continues.
Reuses generate_kc_content.Command().handle() via call_command (Rule 10).

Standards: Rule 10 (one canonical writer: generate_kc_content);
Rule 7 (verify per file on disk); Section 3.6 (audit log after verify);
ISO 9001:2015 7.5.3; ISO 21500:2021 4.3.3 (bulk driver, single writer).
"""
import os
from pathlib import Path

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

from exams.models import KnowledgeComponent


DEFAULT_DIR = "/home/orkoworo/idealogy/tmp/kc_generations"


class Command(BaseCommand):
    help = "Ingest every *.json in DIR into its KC (filename minus .json = KC code)."

    def add_arguments(self, parser):
        parser.add_argument("--dir", type=str, default=DEFAULT_DIR,
                            help="Directory of generation JSON files.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Do not write; only report.")
        parser.add_argument("--strict", action="store_true",
                            help="Abort on first failure instead of continuing.")
        parser.add_argument("--skip-existing", action="store_true",
                            help="Skip KCs that already have misconceptions.")

    def handle(self, *args, **options):
        d = Path(options["dir"])
        dry = options["dry_run"]
        strict = options["strict"]
        skip_existing = options["skip_existing"]

        if not d.is_dir():
            raise CommandError("Not a directory: " + str(d))

        files = sorted(p for p in d.glob("*.json") if p.is_file())
        if not files:
            self.stdout.write("No JSON files in " + str(d))
            return

        ok = 0
        skipped = 0
        failed = 0

        for fp in files:
            code = fp.stem
            try:
                kc = KnowledgeComponent.objects.get(code=code)
            except KnowledgeComponent.DoesNotExist:
                self.stdout.write("WARN " + code + ": KC not found - skipped")
                skipped += 1
                if strict:
                    raise CommandError("KC not found: " + code)
                continue

            if skip_existing and (kc.misconceptions or []):
                self.stdout.write("SKIP " + code + ": already has "
                                  + str(len(kc.misconceptions)) + " misconceptions")
                skipped += 1
                continue

            if dry:
                self.stdout.write("[dry] would ingest " + code
                                  + " from " + str(fp))
                ok += 1
                continue

            try:
                call_command(
                    "generate_kc_content", code,
                    generation_file=str(fp),
                    stdout=self.stdout,
                )
                ok += 1
            except Exception as e:
                self.stdout.write("FAIL " + code + ": " + type(e).__name__
                                  + ": " + str(e)[:120])
                failed += 1
                if strict:
                    raise

        self.stdout.write("--- bulk-ingest done: " + str(ok) + " ok, "
                          + str(skipped) + " skipped, " + str(failed)
                          + " failed, dir=" + str(d))
