"""Split one .docx or .txt per student into individual per-paper JSON files.

Each student doc contains 18 JSON objects (one per model paper) pasted
one after another. This command finds every top-level { ... } block in
the file, validates it as JSON, and writes it to
~/idealogy/tmp/papers/<CODE>.json.

Standards: Rule 10 (one canonical reader); tolerant parsing for
student-produced content; ISO 9001 7.5.3 (auditable per-file output).
"""
import json
import re
import zipfile
from pathlib import Path
from django.core.management.base import BaseCommand, CommandError


def _extract_text(path):
    """Return plain text from a .docx (zip+XML) or .txt file."""
    p = Path(path)
    if p.suffix.lower() == ".docx":
        with zipfile.ZipFile(str(p)) as z:
            xml = z.read("word/document.xml").decode("utf-8", "ignore")
        xml = re.sub(r"</w:p>", "\n", xml)
        text = re.sub(r"<[^>]+>", "", xml)
        text = (text.replace("&amp;", "&").replace("&lt;", "<")
                    .replace("&gt;", ">").replace("&quot;", '"')
                    .replace("&#39;", "'"))
        return text
    return p.read_text(encoding="utf-8", errors="ignore")


def _find_json_objects(text):
    """Yield every balanced top-level { ... } substring."""
    out = []
    depth = 0
    start = None
    in_str = False
    esc = False
    for i, ch in enumerate(text):
        if esc:
            esc = False
            continue
        if ch == "\\":
            esc = True
            continue
        if ch == '"':
            in_str = not in_str
            continue
        if in_str:
            continue
        if ch == "{":
            if depth == 0:
                start = i
            depth += 1
        elif ch == "}":
            depth -= 1
            if depth == 0 and start is not None:
                out.append(text[start:i + 1])
                start = None
    return out


class Command(BaseCommand):
    help = "Split per-student docs into per-paper JSON files."

    def add_arguments(self, parser):
        parser.add_argument("--dir", default="/home/orkoworo/idealogy/tmp/papers_docs")
        parser.add_argument("--out", default="/home/orkoworo/idealogy/tmp/papers")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **opts):
        src = Path(opts["dir"])
        dst = Path(opts["out"])
        if not src.exists():
            raise CommandError("Source dir not found: " + str(src))
        dst.mkdir(parents=True, exist_ok=True)
        total_ok = total_bad = 0
        for f in sorted(src.iterdir()):
            if f.suffix.lower() not in (".docx", ".txt"):
                continue
            text = _extract_text(f)
            blocks = _find_json_objects(text)
            ok = bad = 0
            for raw in blocks:
                try:
                    obj = json.loads(raw)
                except Exception:
                    bad += 1
                    continue
                code = obj.get("code")
                questions = obj.get("questions")
                if not code or not isinstance(questions, list):
                    bad += 1
                    continue
                if opts["dry_run"]:
                    ok += 1
                    continue
                target = dst / (code + ".json")
                with open(target, "w", encoding="utf-8") as fh:
                    json.dump(obj, fh, indent=2, ensure_ascii=False)
                ok += 1
            self.stdout.write(f"{f.name}: ok={ok} bad={bad}")
            total_ok += ok
            total_bad += bad
        self.stdout.write(self.style.SUCCESS(
            f"total: ok={total_ok} bad={total_bad} -> {dst}"
        ))
