"""batch_ingest_all_stages - run 6 stage writers in order for one book.

Standards: Rule 10 (canonical writers preserved); Cooper Stage-Gate
(ordered gates); ISO 8000-8 5.2-5.5 (per-stage completeness);
ISO/IEC/IEEE 29119-3 5.4; Rule 24.
"""
import json
from pathlib import Path

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


STAGES = [
    ("stage3_kc_discovery",     "kc_tag_placeholder_never_runs", None),
    ("stage5_kc_tag",           "kc_tag",                         "tags"),
    ("stage6_kc_misconception", "generate_kc_content_gen",        "candidates"),
    ("stage7_kc_ladder",        "generate_kc_content_ladder",     "ladders"),
    ("stage10_glossary",        "ingest_terms",                   "entries"),
    ("stage11_story",           "ingest_stories",                 "stories"),
]


class Command(BaseCommand):
    help = "Run stage writers in order for one book from one combined JSON."

    def add_arguments(self, parser):
        parser.add_argument("--file", required=True,
                            help="Combined JSON file with all stage payloads.")
        parser.add_argument("--code", required=True,
                            help="Book code, e.g. CH-9, PH-9.")
        parser.add_argument("--dry-run", action="store_true",
                            help="Validate only, no writes.")

    def handle(self, *args, **opts):
        path = Path(opts["file"])
        if not path.exists():
            raise CommandError("file not found: " + str(path))
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception as e:
            raise CommandError("JSON parse failed: " + str(e)[:200])

        code = opts["code"].upper().strip()
        self.stdout.write("=== batch_ingest_all_stages ===")
        self.stdout.write("code=" + code + "  file=" + str(path) +
                          "  dry_run=" + str(bool(opts["dry_run"])))

        # Per-stage writer map (canonical commands only)
        stage_map = self._stage_map(code, data, path, dry_run=opts["dry_run"])

        for stage_key, writer, expected_key in STAGES:
            payload = data.get(stage_key)
            if payload is None:
                self.stdout.write("  SKIP " + stage_key + " (not in file)")
                continue
            present = expected_key is None or bool(payload.get(expected_key)) if isinstance(payload, dict) else False
            self.stdout.write("  HAVE " + stage_key + " (expected key '" + str(expected_key) + "': " + str(present) + ")")

        if opts["dry_run"]:
            self.stdout.write("DRY-RUN complete; no writers invoked.")
            return

        for stage_key, writer, _ in STAGES:
            if stage_key == "stage3_kc_discovery":
                self.stdout.write("  -- " + stage_key + " is discovery; no writer yet --")
                continue
            fn = stage_map.get(writer)
            if fn is None:
                self.stdout.write("  -- " + stage_key + " writer not wired --")
                continue
            try:
                fn(data.get(stage_key) or {})
                self.stdout.write("  OK " + stage_key)
            except Exception as e:
                self.stderr.write("  FAIL " + stage_key + ": " + type(e).__name__ + ": " + str(e)[:200])
                raise

    def _stage_map(self, code, data, path, dry_run):
        """Wire each orchestrator stage to its canonical writer."""
        tmpdir = Path("/tmp") / ("batch_" + code)
        tmpdir.mkdir(parents=True, exist_ok=True)

        def _write(name, payload):
            f = tmpdir / name
            f.write_text(json.dumps(payload), encoding="utf-8")
            return f

        def stage5(payload):
            f = _write("stage5.json", payload)
            call_command("kc_tag", str(f), "--dry-run" if dry_run else "--apply")

        def stage6(payload):
            f = _write("stage6.json", payload)
            # per-KC: call generate_kc_content for each kc in the payload
            kc_codes = []
            if isinstance(payload, dict):
                kc_codes = [c.get("kc_code") for c in (payload.get("candidates") or []) if c.get("kc_code")]
            for kc_code in sorted(set(c for c in kc_codes if c)):
                call_command("generate_kc_content", kc_code,
                             generation_file=str(f))

        def stage7(payload):
            f = _write("stage7.json", payload)
            kc_codes = []
            if isinstance(payload, dict):
                kc_codes = [l.get("kc_code") for l in (payload.get("ladders") or []) if l.get("kc_code")]
            for kc_code in sorted(set(c for c in kc_codes if c)):
                call_command("generate_kc_content", kc_code,
                             ladder_file=str(f))

        def stage10(payload):
            kc_code = "C9-CH00-GLOSSARY"
            if isinstance(payload, dict):
                kc_code = payload.get("kc_code") or kc_code
            f = _write("stage10.json", payload)
            call_command("ingest_terms", kc_code, terms_file=str(f))

        def stage11(payload):
            f = _write("stage11.json", payload)
            call_command("ingest_stories", str(f))

        return {
            "kc_tag": stage5,
            "generate_kc_content_gen": stage6,
            "generate_kc_content_ladder": stage7,
            "ingest_terms": stage10,
            "ingest_stories": stage11,
        }
